Pointer assignment to different types

后端 未结 4 577
遇见更好的自我
遇见更好的自我 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条回答
  •  梦毁少年i
    2021-01-20 06:16

    why can't we assign a pointer to a number in C just like we do with strings?

    int *num;
    num = 4404;
    

    Code can do that if 4404 is a valid address for an int.

    An integer may be converted to any pointer type. Except as previously specified, the result is implementation-defined, might not be correctly aligned, might not point to an entity of the referenced type, and might be a trap representation.
    C11dr §6.3.2.3 5

    If the address is not properly aligned --> undefined behavior (UB).
    If the address is a trap --> undefined behavior (UB).

    Attempting to de-reference the pointer is a problem unless it points to a valid int.

    printf("%d\n", *num);
    

    With below, "Hello" is a string literal. It exist someplace. The assignment take the address of the string literal and assigns that to string.

    char *string;
    string = "Hello";
    

    The point is that that address assigned is known to be valid for a char *.

    In the num = 4404; is not known to be valid (it likely is not).


    What makes a string fundamentally different than other primitive types?

    In C, a string is a C library specification, not a C language one. It is definition convenient to explaining various function therein.

    A string is a contiguous sequence of characters terminated by and including the first null character §7.1.1 1

    Primitive types are part of the C language.

    The languages also has string literals like "Hello" in char *string; string = "Hello";. These have some similarity to strings, yet differ.


    I recommend searching for "ISO/IEC9899:2017" to find a draft copy of the current C spec. It will answer many of your 10 question of the last week.

提交回复
热议问题