Pointer assignment to different types

后端 未结 4 575
遇见更好的自我
遇见更好的自我 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:08

    The type pf a string literal (e.g. "hello world") is a char[]. Where assigning char *string = "Hello" means that string now points to the start of the array (e.g. the address of the first memory address in the array: &char[0]).

    Whereas you can't assign an integer to a pointer because their types are different, one is a int the other is a pointer int *. You could cast it to the correct type:

    int *num;
    num = (int *) 4404;
    

    But this would be considered quite dangerous (unless you really know what you are doing). I.e. do you know what is a memory adress 4404?

提交回复
热议问题