I posted this question on programmers.stackexchange earlier today. I have always assumed that int (*)[]
does not decay into int **
in function parameters but I got multiple responses to my question that suggested that it does.
I have used int (*)[]
heavily in my function parameters but now I have become really confused.
When I compile this function using gcc -std=c99 -pedantic -Wall
void function(int (*a)[])
{
sizeof(*a);
}
I get this error message:
c99 -Wall -pedantic -c main.c -o main.o
main.c: In function ‘function’:
main.c:3:11: error: invalid application of ‘sizeof’ to incomplete type ‘int[]’
make: *** [main.o] Error 1
Which suggests that *a
has the type int []
and not int *
.
Can someone explain if things like int (*)[]
decays into int **
in function parameters and give me some reference (from the standard documents perhaps) that proves why it is so.
int **p declares a pointer on the stack which points to pointer(s) on the heap. Each of that pointer(s) point to an integer or array of integers on the heap.
int* means a pointer to a variable whose datatype is integer. sizeof(int*) returns the number of bytes used to store a pointer. Since the sizeof operator returns the size of the datatype or the parameter we pass to it.
From Code 1, whenever arrays are passed as the arguments to functions, they are always passed by using the 'Pass by reference' mechanism. Because of this, they will decay into pointers in the function parameters.
How Arrays are Passed to Functions in C/C++? A whole array cannot be passed as an argument to a function in C++. You can, however, pass a pointer to an array without an index by specifying the array's name.
Only array types converted to pointer to its first element when passed to a function. a
is of type pointer to an array of int
, i.e, it is of pointer type and therefore no conversion.
For the prototype
void foo(int a[][10]);
compiler interpret it as
void foo(int (*a)[10]);
that's because a[]
is of array type. int a[][10]
will never be converted to int **a
. That said, the second para in that answer is wrong and misleading.
As a function parameter, int *a[]
is equivalent to int **
this is because a
is of array type .
int (*)[]
is a pointer to an array of int
.
In your example, *a
can decay to int*
. But sizeof(*a)
doesn't do decaying; it is essentially sizeof(int[])
which is not valid.
a
can not decay at all (it's a pointer).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With