String pointer and array of chars in c

后端 未结 5 2072
南方客
南方客 2021-02-06 02:19

I just start learning C and found some confusion about the string pointer and string(array of char). Can anyone help me to clear my head a bit?

// source code
ch         


        
5条回答
  •  你的背包
    2021-02-06 02:50

    I think this will help clear it up also:

    int main() {
        char* ptr   = "Hello";
        char  arr[] = "Goodbye";
    
        // These both work, as expected:
        printf("%s\n", ptr);
        printf("%s\n", arr);
        printf("%s\n", &arr);   // also works!
    
        printf("ptr  = %p\n", ptr);
        printf("&ptr = %p\n", &ptr);
        printf("arr  = %p\n", arr);
        printf("&arr = %p\n", &arr);
    
        return 0;
     }
    

    Output:

    Hello
    Goodbye
    Goodbye
    ptr  = 0021578C         
    &ptr = 0042FE2C         
    arr  = 0042FE1C         \__ Same!
    &arr = 0042FE1C         /
    

    So we see that arr == &arr. Since it's an array, the compiler knows that you are always going to want the address of the first byte, regardless of how it's used.

    arr is an array of 7+1 bytes, that are on the stack of main(). The compiler generates instructions tho reserve those bytes, and then populate it with "Goodbye". There is no pointer!

    ptr on the other hand, is a pointer, a 4-byte integer, also on the stack. That's why &ptr is very close to &arr. But what it points to, is a static string ("Hello"), that is off in the read-only section of the executable (which is why ptr's value is a very different number).

提交回复
热议问题