[英]C - returning a pointer to a 2d array
我正在尝试为结构的二维数组编写吸气剂。 我尝试了各种解决方案,而我的 IDE 抱怨所有这些。
static history_t history[3][6];
history_t **get_history(){
return history;
};
根据我的理解,这是正确的。 数组数组是指向指针的指针。 但是,我的 IDE 抱怨指针类型不兼容。 我一直无法找到任何历史签名和访问器的组合,这使我能够返回任何有用的东西。
这在 C 中是可能的吗?
warning: returning 'history_t (*)[6]' {aka 'struct <anonymous> (*)[6]'} from a function with incompatible return type 'history_t **' {aka 'struct <anonymous> **'} [-Wincompatible-pointer-types]
return history;
所以,我的函数不是返回history_t **,而是history_t *[6]。 但是,重新定义签名以返回history_t*[6]
也不起作用。
关于数组、多维数组和指针有很多误解。 我将尝试解释它们之间的差异,然后回答问题。 下面, T
表示类型名称。
T x[3]; /* the type of x is "array of T" */
x
是一个数组。 它具有三个要素。 每个元素都是一个T
。
T *x[3]; /* the type of x is "array of pointer to T" */
x
是一个数组。 它具有三个要素。 每个元素都是一个pointer-to-T
的pointer-to-T
。
T (*x)[3]; /* the type of x is "pointer to an array of three Ts" */
x
是一个指针。 它指向一个数组。 该数组具有三个元素。 每个元素都是一个T
T x[3][6]; /* the type of x is "array of array of six Ts" */
x
是一个数组。 它具有三个要素。 每个元素都是一个包含 6 个T
的数组。 因此x
是一个多维数组,或者更准确地说,是一个二维数组,一个 3×6 的 Ts 数组。
现在,C 中有一个非常重要的规则:类型为“T 的数组”的表达式被转换为指向数组对象初始元素的“指向 T 的指针”,除非它是sizeof
的操作数或地址运算符。 所以,
void f(T*);
void g(void)
{
T x[3];
/* ... */
f(x); /* equivalent to f(&x[0]); */
}
指向数组x
第一个元素的指针在上面的函数调用f(x)
作为参数传递。 数组未通过。 在 C 中无法将数组作为参数直接传递给函数(可以通过将数组包装在结构中来间接完成)。 从函数返回具有相同的语义:不能从函数返回数组(除非它被包装在结构中):
T *f(void)
{
static T x[3];
/* ... */
return x; /* Equivalent to return &x[0]; */
}
返回指向数组x
初始元素的指针。
你的数组被定义为
static history_t history[3][6]; /* static is not relevant in this discussion */
history
类型是“六个history_t
数组的数组”。 如上所述,当它从函数返回时,它将被转换为“指向六个history_t
数组的指针”。 具有“指向六个history_t
s 数组的指针”类型的对象x
定义为
history_t (*x)[6];
要声明返回该类型的函数, x
被函数声明符替换。
history_t (*get_history())[6]; /* function returning pointer to array of six history_ts */
()
优先级高于*
,因此get_history()
周围不需要括号。 要定义这样的函数,需要添加函数体:
static history_t history[3][6];
history_t (*get_history())[6]
{
/* ... */
return history;
}
您有一个静态数组,在您的情况下,该数组的大小必须固定为6
。 所以如果你必须返回一个 6 的指针。
history_t (*get_history())[6] {
return history;
}
然后调用这个函数并使用它的结果,你可以这样做
history_t (*identifier)[6] = get_history();
查看指针、静态和其他...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.