(gcc)多点数组或双指针,用于无警告编译 [英] (gcc) Multi-Dim Array or Double Pointer for Warning-free Compile

查看:89
本文介绍了(gcc)多点数组或双指针,用于无警告编译的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数,有时会用规则的,有时是动态的数组调用。

I have a function, which is called sometimes with regular, sometimes dynamic arrays.

如果我将函数定义为

function_name(int[10][10] a)

并发送int **作为参数,我收到警告。相反,如果我声明

and send int** as a parameter, I get a warning. Opposite, if I declare

function_name(int** a)

并将int [] []作为参数发送(强制转换后)我无法访问函数内部的数组元素。

and send int[][] as a parameter (after casting) I cannot access to array elements inside function.

最正确的方法是什么?

推荐答案

将数组传递给函数时,它衰减到指针到第一个元素。因此,给定:

When an array is passed to a function, it "decays" to a pointer to its first element. So, given:

T a[10];
f(a);

在通话 f(a)中, a 实际上是& a [0] ,即一个指针,类型为 T * & a [0] 的类型)。

In the call f(a), a is actually &a[0], i.e., a pointer, and the type is T * (the type of &a[0]).

当您有一个数组数组时,将应用相同的规则:

When you have an array of arrays, the same rule applies:

T a[10][5];
f(a);

a 再次衰减为指针,等于到& a [0] a [0] 的类型为 T 的数组[5]。因此,& a [0] 的类型为 T 的数组[5]的指针,即如果要声明一个指针 p 来设置等于& a [0] 的指针,则应该执行以下操作: / p>

a decays to a pointer again, equal to &a[0]. a[0] is of type "array [5] of T". So, &a[0] is of type "pointer to array [5] of T", i.e., if you were to declare a pointer p to set equal to &a[0], you would do:

T (*p)[5]; /* parentheses because [] binds tighter than * */
p = &a[0];

鉴于上述情况,并假设您的数组在调用代码中声明为 int a [10] [10]; ,应将函数声明为:

Given the above, and assuming your array is declared in the calling code as int a[10][10];, you should declare your function as:

function_name(int (*a)[10]);

有关更多信息,请参见

For more, see this.

function_name( int [10] [10] a)—您需要在变量名称后指定数组大小: function_name(int a [10] [10])。实际上,由于上​​面提到的衰减,上述内容等效于 function_name(int(* a)[10])

There is a syntax error in function_name(int[10][10] a)—you need to specify the array size after the "variable" name: function_name(int a[10][10]). In fact, the above is equivalent to function_name(int (*a)[10]), because of the "decaying" mentioned above.

编辑:啊,我想我现在明白了。由于上述原因,您不能声明同时使用二维数组和指针指向指针的函数(指针的衰减仅发生一次)。指向指针的指针可能不指向连续数据,并且在每个行中可能具有不同数量的元素。数组数组不能具有这些属性。它们根本不同。

Edit: ah, I think I understand now. You cannot declare a function that takes both a "two dimensional" array and a pointer-to-pointer, for the reasons mentioned above (the "decaying" to pointer happens only once). A pointer to pointer may not point to contiguous data, and may have different number of elements in each "row". An array of arrays doesn't cannot have those properties. They are fundamentally different.

这篇关于(gcc)多点数组或双指针,用于无警告编译的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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