2013-05-19 31 views
0

我有一個計劃:在字符串和管道奇怪的行爲

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); 
    } 

當我comiple這個文件,我總是得到警告:

[[email protected] 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); 結果:

[[email protected] temp]$ ./temp 
hellon 

用這一行,我得到了預期的結果:

[[email protected] temp$ ./temp 
    n is: 5 
    hello 

爲什麼這條線太重要了? 謝謝!

回答

5
buf[n]="\0"; 

應該是

buf[n]='\0'; 

"\0"指針到字符串文字但bufchar陣列。這就是爲什麼警告是關於分配一個指向整數的指針。

您應該只將char指定給buf的元素。我認爲你想給你的數組添加一個空終止符; '\0'是一個值爲0的char因此提供了這一點。

0

取而代之的是

buf[n]="\0"; 

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

雙引號使其字符串,但你想字符。