繁体   English   中英

C中struct的函数返回矩阵的指针

[英]Pointer to function returning matrix of struct in C

我试图创建typedef函数指针,该指针返回结构矩阵。 我试过了:

typedef struct my_struct**  (*func)(void)
typedef struct my_struct[4][4] (*func)(void)

但他们都不起作用。 我的结构矩阵初始化如下:

static struct my_struct matrix[4][4];

我的代码没有使用typedef的2个选项进行编译。 我应该如何创建这个typedef? 谢谢。

数组不能返回。 但是,您可以返回指向数组的指针。 如果要从函数中检索2d数组,应返回此内容。

该函数将返回一个指向4个结构的数组的指针:

struct my_struct (*function(void))[4];

此类型的typedef:

typedef struct my_struct (*type(void))[4];
type* p = function;

数组不能从函数返回。

可以返回一个指向数组第一个元素的指针。 在您的情况下,数组的第一个元素本身就是数组(矩阵中的一行)。 声明指向函数的指针并返回指向数组的指针的语法太不可思议了,无法直接使用。 处理这种情况的最简单,用户友好的方法是使用typedef。

typedef struct my_struct row[4];  // a 4-element row in a matrix
typedef row* (*func)(void);       // pointer-to-function returning pointer-to-row

不能忽略大小, 也不能使用指针代替数组,即

typedef struct my_struct row[];
typedef row* (*func)(void);    // doesn't do what you want

typedef struct my_struct *row;
typedef row* (*func)(void);    // doesn't do what you want

您必须知道在C中不允许将指针返回到本地数组。

row* myfunc(void)
{
   struct my_struct my_matrix[4][4];
   return my_matrix; // will compile, but the behaviour is undefined
                     // a good compiler will warn you
}

您可以通过这种方式将指针返回到静态对象或动态分配的对象。

如果要返回对象而不是指针,则必须使用包装器结构。

typedef struct { struct my_struct elements[4][4]; } wrapper;

wrapper (*foo)(void); //OK
wrapper myfunc(void) 
{
   wrapper w;
   return w; // OK
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM