This might be a stupid question, but I have a little problem with understanding of C Pointers. Even more when it comes to arrays. For example:
char ptr[100];
ptr[0]=10;
fprintf(stderr, "&ptr: %p \n ptr: %p \n*ptr: %d\n", &ptr, ptr, *ptr);
if ( &ptr == ptr ) {
fprintf(stderr, "Why?\n");
}
How is this even possible? ‘ptr’ is at the adress &ptr. And the content of ptr is the same as &ptr. Then why is *ptr = 10 ???
The address of the first element of the array is the same as the address of the array itself.
Except when it is the operand of the
sizeofor address-of&operators, or is a string literal being used to initialize another array in a declaration, an expression of type “N-element array of T” will be implicitly converted (“decay”) to type “pointer to T” and the value will be the address of the first element in the array.If the expression
ais of type “N-element array of T”, then the expression&ais type “pointer to N-element array of T”, orT (*)[N].Given the declaration
then the following are all true:
Expression Type Decays to ---------- ---- --------- a T [N] T * &a T (*)[N] n/a *a T n/aThe expressions
aand&aboth evaluate to the same value (the location of the first element in the array), but have different types (pointer to T and pointer to array of T, respectively).