Why it is possible to assign string to character pointer in C but not an integer value to an integer pointer

后端 未结 3 1787
闹比i
闹比i 2021-01-19 14:56

why in the below code int *p = 22 will give compile time error and ptr will print the value successfully .

int main()
{

/*taking a character pointer and ass         


        
3条回答
  •  清酒与你
    2021-01-19 15:43

    If you have a character array as for example

    char s[] = "Stackoverflow";
    

    then the array designator used in expressions it is converted to pointer to its first element. So you may write

    char *ptr = s;
    

    The pointer ptr now points to the first character of the array s.

    String literals in C are also represented like character arrays and stored in memory like character arrays with the static storage duration.

    So for example the string literal "Stackoverflow" has the type char[14] (including the terminating zero).

    So then you write

    char *ptr = "Stackoverflow";
    

    then this statement in fact the same if there would be

    static char unnamed[] = "Stackoverflow";
    char *ptr = unnamed;
    

    As for this statement

    int *p = 22 ;
    

    then the integer literal is not converted to a pointer to itself. It represents literally the number 22 and nothing more.

    So the compiler issues a message because if you want that the pointer indeed contained the integer value 22 then you have to use a casting.

    The expression

    22 == 22
    

    always yields true.

    While this expression

    "Stackoverflow" == "Stackoverflow"
    

    is not necessary yields true because depending on compiler options the compiler can place coincidental string literals in different memory areas. And in this expression it is the pointers to the first characters of the string literals that are compared.

    Take into account that if you are going to output an integer object pointed to by a pointer you need to use dereferencing. So in any case instead of

    printf("%d",p); 
    

    you should write

    printf("%d", *p); 
    

    Or if you want to output the value stored in a pointer you have to use another format specifier

    printf("%p", p); 
    

提交回复
热议问题