Conceptually as like you assigns string to a char pointer in C, similarly you are assigning an array of integers to p
of type int*
:
When you declares: int *p = (int []){3, 0, 3, 4, 1};
it can be assume to be store in memory like:
p 23 27 31 35 36 37
+----+ +----+----+----+----+----+----+
| 23 | | 3 | 0 | 3 | 4 | 1 | ? |
+----+ +----+----+----+----+----+----+
▲ ▲ ▲ ▲ ▲ ▲
| | | | | // garbage value
p p+1 p+2 p+3 p+4
So basically array allocates continues memory. And you can access elements of array as follows:
p[0] == 3
p[1] == 0
p[2] == 3
p[3] == 4
p[4] == 1
Note:
We do char* str = "hello";
While type of string literals in C is char[N]
not char*
. But thing is in most expressions char[N]
can decays into char*
.
Point:
When you declares an array, for example:
int p[] = {3, 0, 3, 4, 1};
then here p
type is int[5]
and &p
pointer to an array
= types is: int(*)[5]
Whereas in declaration:
int *p = (int []){3, 0, 3, 4, 1};
p
pointer to first element and type of p
is int*
and &p
type is int**
. (this is similar to string assignment to char pointer).
In first case p[i] = 10;
is legal for 0 <= i <= 4
, But in second case you are writing on read only memory-illegal memory operation-segmentation fault.
point:
Not following is also valid declaration:
int *p = (int *){3, 0, 3, 4, 1};
Q Actually I want to know, Is this array will stored in memory or not as it doesn't have a name?
Of-course array's stored in memory but its just pointed by p
(p
is not name of array), no other name is 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 array, its exactly similar to:
char* s = "hello";
char c = 'A';
s = &c;
and now you loses the address of "hello"
.
Memory for constant comes from static segment, when you declares. Any int-array of char string literal get store there. When your declaration runs address assigned to pointer variables. But constant don't have any name-but value. In both cases array and string "hello"
becomes the part of executable in data section. (you can disassemble to find there values).
int *p
... – Frowstymalloc()
has no name, either. – Jefferyjeffiechar * p = "some words";
doesn't have a "name", either, but would you think this wasn't "stored in memory" either? – Lustygoto
orlongjmp
. – Bandy(int []){...}
is an object with no name? – Congdon(int []){...}
declares an object. I am surprised!. – Congdonhello
will stored in memory?" – Lusty