On page 103 in the book “Expert C Programming: Deep C Secrets” by Peter Van Der Linden there is a table about the difference between arrays and pointers.
One issue I don't really understand – direct quote:
Pointer: Typically points to anonymous data
Array: Is a named variable in its own right
What does this mean? Since you can do the following:
#include <stdio.h>
#include <stdlib.h>
int main(void){
int x[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int *y = malloc(9*sizeof(int));
printf("sizeof(x) == %zu\n", sizeof(x));
printf("&(x[2]) = %p\n", (void*)&(x[2]));
printf("sizeof(y) == %zu\n", sizeof(y));
printf("&(y[2]) = %p\n", (void*)&(y[2]));
return 0;
}
Output:
sizeof(x) == 36
&(x[2]) = 0x7fffffffe5f8
sizeof(y) == 8
&(y[2]) = 0x800e18008
I don't see how y
is less of a named variable than x
.
The author could have been more clear here, I agree. A pointer is a named variable in its own right too, but if it points to an array, it doesn't have any information about the length of the array. In fact, it doesn't know that it's pointing to an array. The syntax p[100]
is valid (although undefined) even if p
was assigned the address of a single int
or other data type.
This is why when an array is passed as an argument to a function, it is either:
To more clearly demonstrate this distinction, try this:
int arr[3] = { 1,2,3 };
int *ptr;
ptr = &arr;
I get the following compilation warning:
'=': 'int *' differs in levels of indirection from 'int (*)[3]'
But, if you change ptr
to point to arr
's first element (which is what happens when arr
decays to a pointer), there's no problem:
ptr = &arr[0];