为什么C不允许返回数组类型? [英] Why does C disallow an array return type?

查看:89
本文介绍了为什么C不允许返回数组类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是为什么有效用C

 为int *富(int类型的,INT B){
...
}

但这是无效的。

  INT []美孚(INT A,INT B){
...
}


解决方案

的语法是有点好笑。

  INT美孚(INT A,INT B)[]
{
    ...
}

但它不反正不允许的。见6.7.5.3 n1256第1款规定,函数声明。


  

一个函数声明不得指定返回类型是函数类型或数组类型。


您可以返回指向数组的指针:

  INT(*富(int类型的,INT B))[]; //奇怪的语法,n'est-CE PAS?

但是,你可能也只是返回一个指针代替,因为下面是等价的:

  int数组[] = {...};
为int * X =阵列(* Y)[] =&放大器;阵列;
X [0];
(* Y)[0]; //同上,只是更繁琐的语法

通常,如果一个函数需要返回 INT 的数组,你要么在返回指针或通过指针以下之一:

 为int * FUNC(int类型的,INT B); //通过FUNC分配
无效FUNC(INT A,INT B,INT *数组); //呼叫者分配
无效FUNC(INT A,INT B,INT **数组); //通过FUNC分配

在结构 - 黑客也适用于具有固定大小的数组:

 结构{INT改编[50]; } array_struct;
结构array_struct FUNC(int类型的,INT B);

但不建议这样做,除非数组是很小的。

理由:

阵列往往很大,而且往往有一个尺寸不知道,直到运行时。由于参数和返回值是使用堆栈,寄存器(所有的ABI我所知道的)过去了,栈有固定的大小,它是有点危险是传递这样一个大对象在堆栈中。一些ABI还没有很好地处理大的返回值,这可能导致生成返回值的额外副本。

以下code也可以是危险的:

 无效FUNC(...)
{
    INT ARR [BIG_NUMBER] //潜在的堆栈溢出
    为int * PTR =的alloca(的sizeof(int)的* BIG_NUMBER); //潜在的堆栈溢出
}

Why is this valid in C

int * foo(int a,int b){
...
}

but this is invalid

int [] foo(int a,int b){
...
}

解决方案

The syntax is somewhat funny.

int foo(int a, int b) []
{
    ...
}

But it's not allowed anyway. See n1256 6.7.5.3 paragraph 1, "Function declarators".

A function declarator shall not specify a return type that is a function type or an array type.

You can return pointers to arrays:

int (*foo(int a, int b)) []; // Weird syntax, n'est-ce pas?

But you might as well just return a pointer instead, since the following are equivalent:

int array[] = { ... };
int *x = array, (*y)[] = &array;
x[0];
(*y)[0]; // same as above, just with more cumbersome syntax

Typically, if a function needs to return an array of int, you either return the pointer or pass the pointer in. One of the following:

int *func(int a, int b); // Allocated by func
void func(int a, int b, int *array); // Allocated by caller
void func(int a, int b, int **array); // Allocated by func

The "struct-hack" also works for arrays that have a fixed size:

struct { int arr[50]; } array_struct;
struct array_struct func(int a, int b);

But this is not recommended unless the array is small.

Rationale:

Arrays are often large, and often have a size not known until runtime. Since parameters and return values are passed using the stack and registers (on all ABIs I know of), and the stack has a fixed size, it is somewhat dangerous to pass such a large object around on the stack. Some ABIs also don't gracefully handle large return values, potentially causing extra copies of return values to be generated.

The following code can also be dangerous:

void func(...)
{
    int arr[BIG_NUMBER]; // potential for stack overflow
    int *ptr = alloca(sizeof(int) * BIG_NUMBER); // potential for stack overflow
}

这篇关于为什么C不允许返回数组类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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