Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does "int (*)[]" decay into "int **" in a function parameter?

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.

like image 468
wefwefa3 Avatar asked Jan 10 '15 16:01

wefwefa3


People also ask

What does int * p do in C++?

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.

What does int *) do in C?

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.

Why do arrays decay into pointers?

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 do you pass an array of pointers to a function in C++?

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.


2 Answers

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 .

like image 79
haccks Avatar answered Oct 30 '22 13:10

haccks


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).

like image 36
nullptr Avatar answered Oct 30 '22 13:10

nullptr