如何解决“警告:赋值从指针生成整数而不进行强制转换”使用 char malloc
我正在编写代码以从路径中删除文件名和类型。但是,我收到有关更改字符内容的行的警告。我怎样才能摆脱警告?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *getPath(char *fullPath){
char *aux;
int a,b,c;
aux = malloc(50 * sizeof(char));
aux = fullPath;
a = strlen(aux);
for(b=0; b<a; b++){
if (aux[b] == '/'){
c = b;
}
}
for(c; c < a; c++){
///PROBLEM HERE
aux[c] = "";
}
///PROBLEM HERE
return aux;
}
int main(void) {
char C[50];
char *path,*filename;
scanf("%s",C);
path = getPath(C);
printf("%s",path);
}
解决方法
aux[c] = ""; // here "" is a char *
aux
是 char *
,因此 aux[c]
是 char
(不是字符串 ""
)
aux[c] = '\0';
正如注释中所写,其余代码中还有其他错误:例如 aux
值被擦除。
尝试修复整个代码。
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
bool getPath(char *const strippedPath,const int strippedPath_buflen,const char *const fullPath){
int b=strlen(fullPath);
for(;;){
--b;
if(b<0)
return false;
if('/'==fullPath[b])
break;
}
if(strippedPath_buflen<b+1)
return false;
strncpy(strippedPath,fullPath,b);
strippedPath[b]='\0';
return true;
}
int main(void) {
for(;;){
char C[50]={};
printf("> ");
fflush(stdout);
scanf("%s",C);
if(0==strcmp("quit",C))
break;
char path[3+1]={'X','X','X'};
if(getPath(path,4,C))
printf("%s\n",path);
else
printf("err\n");
}
return 0;
}
> aaaa/b.txt
err
> aaa/b.txt
aaa
> a/c/b.txt
a/c
> aa/b.txt
aa
> a/b.txt
a
> a/
a
> /b.txt
> b.txt
err
> quit
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。