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

时间:2013-05-19 12:53:43

标签: 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

为什么这条线如此重要? 谢谢!

2 个答案:

答案 0 :(得分:5)

buf[n]="\0";

应该是

buf[n]='\0';

"\0"是字符串文字的指针,但bufchar数组。这就是为什么警告是关于指定一个整数的指针。

您应该只为char的元素分配buf。我假设你想为你的数组添加一个null终止符; '\0'char,其值为0,因此提供此功能。

答案 1 :(得分:0)

而不是这个

buf[n]="\0";

DO

buf[n]='\0'; //with single quotes

双引号使它成为字符串,但你需要字符。

相关问题