Conceptually, how do you assign a string to a char pointer in C, in the same way you assign an array of integers p type int* :
When you declare: int *p = (int []){3, 0, 3, 4, 1}; , we can assume that it is stored in memory, for example:
p 23 27 31 35 36 37 +----+ +----+----+----+----+----+----+ | 23 | | 3 | 0 | 3 | 4 | 1 | ? | +----+ +----+----+----+----+----+----+ β² β² β² β² β² β² | | | | | // garbage value p p+1 p+2 p+3 p+4
Thus, basically an array allocates memory. And you can access the elements of the array as follows:
p[0] == 3 p[1] == 0 p[2] == 3 p[3] == 4 p[4] == 1
Note:
We do char* str = "hello"; So far, the type of string literals in C is char[N] not char* . But the point in most char[N] expressions can fall into char* .
Point :
When you declare an array, for example:
int p[] = {3, 0, 3, 4, 1};
then here p type int[5] and &p pointer to an array = types: int(*)[5]
While in the declaration:
int *p = (int []){3, 0, 3, 4, 1};
p pointer to the first element and type p is int* and &p type is int** . (this is like assigning a string to a char pointer).
In the first case, p[i] = 10; is legal for 0 <= i <= 4 , but in the second case, you write a read error on a read-only memory operation.
paragraph:
The following announcement also should not be:
int *p = (int *){3, 0, 3, 4, 1};
Q Actually, I want to know whether this array will be stored in memory or not, since it has no name?
A massive array stored in memory, but its newly designated p ( p not the name of the array); there is no other name for it. Suppose if you do:
int *p = (int []){3, 0, 3, 4, 1}; int i = 10; p = &i;
Now you have lost the address of the array, it looks exactly like:
char* s = "hello"; char c = 'A'; s = &c;
and now you are losing the address "hello" .
The memory for the constant comes from the static segment when you declare. Any char string literal int array gets storage there. When your ad runs the address assigned to pointer variables. But the constant does not have a name, but a value. In both cases, the array and the string "hello" become part of the executable in the data section. (you can parse to find the values ββthere).