我有一个程序:
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);
}
当我编译这个文件时,我总是收到警告:
[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]
没有这一行 printf("n is: %d\n",n);
结果是:
[esolve@kitty temp]$ ./temp
hellon
通过这一行,我得到了预期的结果:
[esolve@kitty temp$ ./temp
n is: 5
hello
为什么这条线如此重要? 谢谢!
最佳答案
buf[n]="\0";
应该是
buf[n]='\0';
"\0"
是一个指向字符串文字的指针,而buf
是一个char
数组。这就是警告是关于将指针分配给整数的原因。
您应该只将 char
分配给 buf
的元素。我假设您想在数组中添加一个空终止符; '\0'
是一个值为 0 的 char
,所以提供了这个。
关于c - 字符串和管道中的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16634839/