c - strange behavior in character string and pipe -
i have program:
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); // line important! buf[n]="\0"; // line triggers warning。 printf("%s\n",buf); } when comiple file, warning:
[esolve@kitty temp]$ gcc -o temp temp.c temp.c: in function ‘main’: temp.c:38:9: warning: assignment makes integer pointer without cast [enabled default] and without line printf("n is: %d\n",n); result :
[esolve@kitty temp]$ ./temp hellon with line, expected result:
[esolve@kitty temp$ ./temp n is: 5 hello why line important? thanks!
buf[n]="\0"; should be
buf[n]='\0'; "\0" pointer string literal buf char array. that's why warning assigning pointer integer.
you should assign char element of buf. presume wanted add null terminator array; '\0' char value 0 provides this.
Comments
Post a Comment