简体   繁体   English

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

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

I'm trying to create typedef to function pointer which returns matrix of struct. 我试图创建typedef函数指针,该指针返回结构矩阵。 I tried: 我试过了:

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

but none of them worked. 但他们都不起作用。 My matrix of struct is initialized like: 我的结构矩阵初始化如下:

static struct my_struct matrix[4][4];

my code didn't compiled with the 2 options of typedef. 我的代码没有使用typedef的2个选项进行编译。 How should I create this typedef? 我应该如何创建这个typedef? Thanks. 谢谢。

Arrays cannot be returned. 数组不能返回。 You can however return a pointer to an array. 但是,您可以返回指向数组的指针。 This is what should be returned if you want to retrieve your 2d array from a function. 如果要从函数中检索2d数组,应返回此内容。

The function would return a pointer to an array of 4 structs: 该函数将返回一个指向4个结构的数组的指针:

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

typedef of this type: 此类型的typedef:

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

Arrays cannot be returned from functions. 数组不能从函数返回。

One can return a pointer to the first element of an array. 可以返回一个指向数组第一个元素的指针。 In your case, the first element of your array is itself an array (a row in a matrix). 在您的情况下,数组的第一个元素本身就是数组(矩阵中的一行)。 The syntax needed to declare a pointer to a function returning a pointer to an array is too arcane to be used directly. 声明指向函数的指针并返回指向数组的指针的语法太不可思议了,无法直接使用。 The most simple, user-friendly way to deal with the situation is to use a typedef . 处理这种情况的最简单,用户友好的方法是使用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

You cannot omit the size and cannot use a pointer instead of an array, ie 不能忽略大小, 也不能使用指针代替数组,即

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

You have to know that returning a pointer into a local array is not allowed in C. 您必须知道在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
}

You can return a pointer to a static object or to a dynamically allocated object this way. 您可以通过这种方式将指针返回到静态对象或动态分配的对象。

If you want to return objects and not pointers, you have to use a wrapper struct. 如果要返回对象而不是指针,则必须使用包装器结构。

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