开发者

Some 'predict the outputs' with pointers

开发者 https://www.devze.com 2022-12-20 02:06 出处:网络
Help me in solving 2 questions on pointers: 1)Please tell me why do I get \'segmentation fault\' when I run following snippet

Help me in solving 2 questions on pointers:

1)Please tell me why do I get 'segmentation fault' when I run following snippet

main()  
{   
    char *str1 = "united";  
    char *str2 ="front";  
    char *str3;  
    str3 = strcat(str1,str2);  
    printf("\n%s",str3);  
}

2)Why don't I get output in following code:

main()  
{  
    char str[10] = {0,0,0,0,0,0,0,0,0,0};  
    char *s; 
    int i开发者_StackOverflow中文版;   
    s = str;  
    for(i=0 ; i<=9;i++)  
    {  
        if(*s)  
            printf("%c",*s);
        s++; 
    }   
}

Thank u.


  1. You should review how strcat works. It will attempt to rewrite the memory at the end of your str1 pointer, and then return the destination pointer back to you. The compiler only allocated enough memory in str1 to hold "united\0" (7 chars), which you are trying to fill with "unitedfront\0" (12 chars). str1 is pointing to only 7 allocated characters, so there's no room for the concatenation to take place.

  2. *s will dereference s, effectively giving you the first character in the array. That's 0, which will evaluate to false.


1) compiles to something like:

const char _str1[7] = "united";
const char _str2[6] ="front";
char *str1 = _str1;
char *str2 = _str2;
strcat(str1,str2);
str3 = str1;

str1 points to a buffer which is exactly 7 bytes long and is filled with 6 characters. The strcat put another 5 bytes into that buffer. 7 bytes cannot hold 11 characters. The C there is no magic! If you do not explicitly allocate space for something, no one else does it either.....

2) isn't going to print anything. It steps through an array, every element of which is 0. It then tests if the current item (*s) is not 0 (if(*s)) , and if so, prints that item as a character. However, since the item always is 0, it always fails to test.


for question 2, think about what the following line does:

if(*s)
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号