我有一个程序:
int main()
{
int* p_fd = (int*)malloc(2*sizeof(int));
char buf[100];
pipe(p_fd);
write(p_fd[1],"hello", strlen("hello"));
int n;
n = read(p_fd[0],buf,100);
//printf("n is: %d\n",n); // this line is important!
buf[n]="\0"; // this line triggers warning?
printf("%s\n",buf);
}
Run Code Online (Sandbox Code Playgroud)
当我编辑这个文件时,我总是得到警告:
[esolve@kitty temp]$ gcc -o temp temp.c
temp.c: In function ‘main’:
temp.c:38:9: warning: assignment makes integer from pointer without a cast [enabled by default]
Run Code Online (Sandbox Code Playgroud)
如果没有这一行printf("n is: %d\n",n);
,结果是:
[esolve@kitty temp]$ ./temp
hellon
Run Code Online (Sandbox Code Playgroud)
有了这一行,我得到了预期的结果:
[esolve@kitty temp$ ./temp
n is: 5
hello
Run Code Online (Sandbox Code Playgroud)
为什么这条线如此重要?谢谢!
buf[n]="\0";
Run Code Online (Sandbox Code Playgroud)
应该
buf[n]='\0';
Run Code Online (Sandbox Code Playgroud)
"\0"是一个指向字符串文字的指针,但它buf是一个char数组.这就是为什么警告是关于指定一个整数的指针.
你应该只分配一个char元素buf.我假设你想为你的数组添加一个null终止符; '\0'是char值0,所以提供此.