I have the following program. However, I can’t understand why I have to pass the address of the array. When they are both pointing to the same address. Which is the address of the first element of the array of int’s.
I get a warning when I try and do this “assignment from incompatible pointer type”:
ptr = var;
Complete source code:
void print_values(int (*ptr)[5])
{
size_t i = 0;
for(i = 0; i < 5; i++) {
printf("%d: [ %d ]\n", i, (*ptr)[i]);
}
}
int main(void)
{
/* declare a pointer to an array integers */
int (*ptr)[5] = NULL;
/* array of integers */
int var[] = {1, 2, 3, 4, 5};
/* assign the address of where the array is pointing to (first element) */
ptr = &var;
/* Both are pointing to the exact same address */
printf("var [ %p ]\n",(void*)var);
printf("&var [ %p ]\n", (void*)&var);
print_values(ptr);
return 0;
}
I compile the code with gcc 4.4.4 c89 -Wall -Wextra -O0
It’s purely a type issue.
In most expression contexts the name of an array (such as
var) decays to a pointer to the initial element of the array, not a pointer to the array. [Note that this doesn’t imply thatvaris a pointer – it very much is not a pointer – it just behaves like a pointer to the first element of the array in most expressions.]This means that in an expression
varnormally decays to a pointer to anint, not a pointer to an array ofint.As the operand of the address-of operator (
&) is one context where this decay rule doesn’t apply (the other one being as operand of thesizeofoperator). In this case the type of&varis derived directly from the type ofvarso the type is pointer to array of 5int.Yes, the pointers have the same address value (the address of an arrays first element is the address of the array itself), but they have different types (
int*vsint(*)[5]) so aren’t compatible in the assignment.ISO/IEC 9899:1999 6.3.2.1/4: