简体   繁体   中英

Why does the declaration int (*f())[]; doesn't give an error or warning?

The following statement declares a function which takes no argument and returns a pointer to an integer array.

int (*f())[];

It returns a pointer to an integer array of size _____
We didn't specify the size of the array, so it should give some kind of warning or error.

I am asking this because when we pass a 2-D array or a pointer to an integer array to a function, we are always supposed to specify the dimension while declaring the pointer in the formal arguments.
So, Why is this declaration allowed?
Is there any specific reason for not throwing an error or warning for this kind of declaration?
Is it that we can also omit the dimension while defining this function OR it becomes inevitable to specify the dimension while defining it?
For a better understanding, Please give a dummy definition of this function as well.

Throw it into cdecl and you'll see:

 int (*f())[];

declare f as function returning pointer to array of int

This happens because of array to pointer decay .

int (*f())[];

fine

int (*f())[][];

error

int (*f())[][8];

fine

When you pass or return an array, you must give all dimensions other than the first one. The working definition.

Example implementation:

int (*f())[]
{
    static int array[8];
    static int *aptr = array;
    return &aptr;
}

You might do something like this for lazy initialization (including lazy allocation) which is its own topic.

" We didn't specify the size of the array, so it should give some kind of warning or error. "

We don't need to specify the size of the array to point to. To know the exact size of the array to point to in the caller is not required. f just returns a pointer, not an array.

" I am asking this because when we pass a 2-D array or a pointer to an integer array to a function, we are always supposed to specify the dimension while declaring the pointer in the formal arguments. "

No, that's not true. If you pass a pointer to an array as argument to a function, it doesn't matter if you declare the parameter to be a pointer to an array of 10 or 50 elements or even not to point to an array and just declare a single pointer.

int f (int *p)
{
    return *p;
}

int a[7];
int b = f(a);

is perfectly valid.

int* p is equal to int p[] as well as equal to int p[239] .

The pointer passed is treated as single pointer.

In case of passing pointers to 2D arrays (or more specific a pointer to an array of int ) in the caller, the first can be omitted but last dimension need to be specified.

int f (int (*p)[5])
{
    return **p;
}

int a[4][5];
int b = f(a);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM