Why must int pointer be tied to variable but not char pointer?

前端 未结 8 698

I am not sure if I worded the question correctly, but here it is spelled out:

char * cp = \"this is a char pointer\";

The code above, based

8条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-10 10:17

    the compiler does not allocate memory for a string neither for an integer if you declare char* or int*.

    the memory is allocated only if you specify it : char* p1 = "string"; for a const string or char* p2 = (char*)malloc(5*sizeof(char)); for a normal dynamically allocated array of char which can be modified or char p3[10]; for array of char which can be use as a string.

    then you can fill p2 and p3 with the string you want : strcpy (p2 , "Hi");

    you cannot not do the same with p1 : strcpy(p1 , "Hi"); will certainly crash the program.

    then when you write int* ip;,int x;, p=&x; : you allocate the memory for the int with the line int x;.

    yo can allocate the memory also with int *ip2 = (int*)malloc(sizeof(int)) then you have not to associate the pointer with a variable. the int can be changed with *ip2 = 3;.

提交回复
热议问题