简体   繁体   中英

Pointer to function returning matrix of struct in C

I'm trying to create typedef to function pointer which returns matrix of struct. 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. How should I create this 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.

The function would return a pointer to an array of 4 structs:

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

typedef of this type:

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 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.

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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