Pointer assignment to different types

后端 未结 4 604
遇见更好的自我
遇见更好的自我 2021-01-20 05:39

We can assign a string in C as follows:

char *string;
string = \"Hello\";
printf(\"%s\\n\", string); // string
printf(\"%p\\n\", string); // memory-address
<         


        
4条回答
  •  無奈伤痛
    2021-01-20 06:03

    What makes a string fundamentally different than other primitive types?

    A string seems like a primitive type in C because the compiler understands "foo" and generates a null-terminated character array: ['f', 'o', 'o', '\0']. But a C string is still just that: an array of characters.

    My question then is, why can't we assign a pointer to a number in C just like we do with strings?

    You certainly can assign a pointer to a number, it's just that a number isn't a pointer, whereas the value of an array is the address of the array. If you had an array of int, then that would work just like a string. Compare your code:

    char *string;
    string = "Hello";
    printf("%s\n", string); // string
    printf("%p\n", string); // memory-address
    

    to the analogous code for an array of integers:

    int numbers[] = {1, 2, 3, 4, 5, 0};
    int *nump = numbers;
    printf("%d\n", nump[0]); // string
    printf("%p\n", nump);    // memory-address
    

    The only real difference is that the compiler has some extra syntax for arrays of characters because they're so common, and printf() similarly has a format specifier just for character arrays for the same reason.

提交回复
热议问题