array
int a[10]
The a in is the array name, which points to the first element in the array. But when it is used as sizeof
an operand, or when using an &
address, it should a
be considered as an array.
Array name and array name take address
Let's look at an example:
int a[10] = {0};
printf("%p, %p\n", a, &a);
The print result is 0xbfc077b4, 0xbfc077b4
. Both values are the same, but their types are different. a
Represents the address of the first element of the array, type is int*
, &a
represents a
the address of the array, type is int (*)[10]
, a pointer to an array containing 10 int elements.
We can use the following example to verify the above conclusion:
int b[10] = {0};
printf("%p, %p, %p, %p\n", b, &b, b+1, &b+1);
The print result is 0xbf890214, 0xbf890214, 0xbf890218, 0xbf89023c
. a+1
The stride is the size of an array element, while &a+1
the stride is the size of the entire array.
array as function parameter
When an array is a function parameter, its type degenerates to a pointer. Take a look at an example:
int test_func(int a[])
{
printf("the value is %d\n", sizeof(a));
return 0;
}
int main(int argc, char* argv[])
{
int arr[10] = {0};
test_func(arr);
return 0;
}
In the above example, it sizeof(a)
is 4, because when the array is used as a function parameter, it degenerates into a pointer, so sizeof(a)
it is actually sizeof(int*)
.