我可以返回指向VLA的指针吗? [英] Can I return pointer to VLA?

查看:90
本文介绍了我可以返回指向VLA的指针吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这样的函数原型在C语言中有效吗?

Is such function prototype valid in C?

int (*func())[*];

如果是的话,我该如何定义这些功能?

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

推荐答案

来自C标准(6.2.1标识符范围)

From the C Standard (6.2.1 Scopes of identifiers)

  1. ...(函数原型是对函数的声明,该函数声明其参数的类型.)
  1. ...(A function prototype is a declaration of a function that declares the types of its parameters.)

和(6.7.6.2数组声明符)

and (6.7.6.2 Array declarators)

  1. ...如果大小为*而不是表达式,则数组类型为未指定大小的可变长度数组类型,只能 可以在具有函数原型作用域的声明或类型名称中使用;
  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.

请考虑到1)函数可能没有数组的返回类型,而2)可变长度数组具有自动存储持续时间.因此,如果可以返回这样的数组,则该函数具有未定义的行为.请参见6.7.6.2数组声明符:

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如果一个标识符被声明为具有可变修改的类型,则它 应为普通标识符(如6.2.3所定义),没有 链接,并且具有块作用域或函数原型作用域. 如果 标识符被声明为具有静态或线程的对象 存储期限,不得使用可变长度的数组类型.

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.

我知道两种解决您问题的方法.动态分配一个数组,然后将poinetr返回到其第一个元素.或将数组打包在结构中.在这种情况下,您可以将函数的整个结构作为右值返回.

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.

这篇关于我可以返回指向VLA的指针吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆