c - 字符串和管道中的奇怪行为

标签 c string pipe

我有一个程序:

    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/

相关文章:

c - C语言中如何使用char

python - 为什么 .join() 是字符串的属性而不是列表?

javascript - 如何使用javascript替换字符串中所有匹配的纯文本字符串(但不是标签或属性)?

检查非对称回文

C 文件读取不正确

c - 使用未命名管道发送信息

Node.js POST 文件到服务器

C 使用 exec 和 pipe 创建许多子进程

c - 将文件中的事件预处理器符号导入 Eclipse CDT

c - 从字符串元素中取值并将取值与两位数相加