I am confused... what a actually is? It is said to be of type char*
If you define an array like you do: char a[5] = "hill;"
.
Then the following holds:
1. a implicitly decayed to char *: decayed to a pointer to the first element
2. &a[0] is of type char *: pointer to the first element
3. &a is of type char (*)[5]: pointer to an array which starts at the first element
All of them points to the same memory address but they are of a different type. Note that in case 1 the array name will be decayed.
Oh well, the exact same address is printed out. Please explain me, what is happening here
That means if you print out the address of either a
or &a
it will be the same. Also remember that if you want to print an address you cast the pointer to a void*
and not just to an int
.
It is a pointer, its value must be an address of the first character. And a itself must have an address. Surely these two addresses have to be different as a is of type char* and the address it hold points to char.
With your assumption that the a
points implicitly to the first element you're right. Also this variable has an address where the value that point to something is stored.
Edit #1:
Proof of the above:
Becaue several comments challenged, what I explained about a
, &a[0]
and &a
here is the proof. Therefore I wrote this little not compiling C code:
int main()
{
char a[5];
double b;
/* the following fails */
b = a; /* decay to char * */
b = &a[0]; /* char * */
b = &a; /* char (*)[5] */
}
The compiler will fail and output errors and the expected type.
../src/SO_Test_C.c:6:7: error: incompatible types when assigning to type ‘double’ from type ‘char *’
b = a;
^
../src/SO_Test_C.c:7:7: error: incompatible types when assigning to type ‘double’ from type ‘char *’
b = &a[0];
^
../src/SO_Test_C.c:8:7: error: incompatible types when assigning to type ‘double’ from type ‘char (*)[5]’
b = &a;
^
sizeof():
Here is what the different sizeof()
operations are returning:
sizeof(a) --> Array size: 5
sizeof(&a[0]) --> Pointer size: 8 (64bit) / 4 (32bit)
sizeof(&a)) --> Pointer size: 8 (64bit) / 4 (32bit)