I have a question about syntax of pointer to arrays. Well we know arrays are pointers themselves(what our uni professor said) so why when we point to them with another pointer (which would be a pointer to pointer) we use this syntax:
int array[10];
int *pointer = array;
Instead of this syntax:
int array[10];
int **pointer = &array;
Although i know this would be correct using malloc but why not in the normal way, is it a compiler or syntax thing or i am wrong somewhere else??
Well we know arrays are pointers themselves
No. Arrays are not pointers. Arrays are arrays. Except when it is the operand of the sizeof
or the unary &
operator, an expression of type "N-element array of T
" will be converted ("decay") to an expression of type "pointer toT
" and the value of the expression will be the address of the first element of the array. However, no storage is set aside for a pointer in addition to the array elements themselves.
So, given the declaration
int array[10];
the type of the expression array
is "10-element array of int
"; unless array
is the operand of sizeof
or unary &
, it will decay to type int *
. So
int *ptr = array;
works.
The type of &array
is not int **
; the type is int (*)[10]
, or "pointer to 10-element array of int
". You'd declare and initialize such a pointer as
int (*ptr)[10] = &array;