Can I return pointer to VLA?

两盒软妹~` 提交于 2019-12-13 19:17:18

问题


Is such function prototype valid in C?

int (*func())[*];

And if it is, how can I define such functions?


回答1:


From the C Standard (6.2.1 Scopes of identifiers)

  1. ...(A function prototype is a declaration of a function that declares the types of its parameters.)

and (6.7.6.2 Array declarators)

  1. ...If the size is * instead of being an expression, the array type is a variable length array type of unspecified size, which can only be used in declarations or type names with function prototype scope;

So you may not specify return type of the function such a way as you showed.

Take into account that 1) functions may not have return types of arrays and 2) variable length arrays have automatic storage duration. Thus if such an array could be returned the function had undefined behaviour. See 6.7.6.2 Array declarators:

2 If an identifier is declared as having a variably modified type, it shall be an ordinary identifier (as defined in 6.2.3), have no linkage, and have either block scope or function prototype scope. If an identifier is declared to be an object with static or thread storage duration, it shall not have a variable length array type.

I know two approaches to your problem. Either allocate an array dynamically and return a poinetr to its first element. Or pack an array in a structure. In this case you can return the whole structure from a function as an rvalue.




回答2:


You should return a pointer to an incomplete array type instead as * notation for variable-length arrays is only valid in parameter lists.

Example prototype and function definition:

extern float (*first_row(unsigned, unsigned, float (*)[*][*]))[];

float (*first_row(unsigned n, unsigned m, float (*matrix)[n][m]))[]
{
    return *matrix;
}

You'd invoke it like this:

unsigned n = 3, m = 4;
float matrix[n][m];
float (*row)[m] = first_row(n, m, &matrix);

Note that it is undefined behaviour to return a pointer to an array (variable-length or otherwise) that has been declared within the function if it has automatic storage duration. This implies that you can only return a pointer to a variable-length array that you passed in as an argument or allocated dynamically.




回答3:


Tecnically you can, but it's not a good idea.

int * func(size_t s)
{
    int array[s];
    return array;
}

After being defined a variable length array is no different than a regular array, so it decays to a pointer when you try to return it. Returning a pointer to a local variable results in undefined behaviour.



来源:https://stackoverflow.com/questions/29576038/can-i-return-pointer-to-vla

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!