Ray Burns Ray Burns - 2 months ago 15
C Question

How do I return a struct (from a function) containing an array with the correct elements in that array?

I'm making a program that returns a struct containing an array, but the elements in the array are completely wrong. I keep searching for an answer on this site, Google, and even Bing and nothing. The best I can find are answers like this:


Functions can't return arrays in C.

However, they can return structs. And structs can contain arrays...


from How to make an array return type from C function?

Now, how do I fix this without the use of pointers?

#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <ctype.h>

struct Codes{
int as;
int a[];
};

struct Codes create(int as){
int a[as];
for(int j = 0;j<as;j++)
a[j]=j+1;
struct Codes c;
c.as = as;
c.a[c.as];
for(int i=0; i<as; i++)
c.a[i] = a[i];

for(int i=0; i<as; i+=1)
printf("%d \n", c.a[i]);

return c;
}

int main(int argc, char **argv) {

struct Codes cd;
int as = 4;
cd = create(as);

for(int i=0; i<4; i+=1)
printf("%d \n", cd.a[i]);

}


Actual output:

1
2
3
4
0
0
2
-13120


Expected output:

1
2
3
4
1
2
3
4

Answer

structs with flexible value are not meant to be manipulated by value, only by pointer.

You cannot return a struct with a flexible member by value, because C does not know how many items it needs to allocate to the return value, and how many bytes it needs to copy.

Allocate your struct in dynamic memory using malloc of sufficient size, copy your data into it, and return a pointer to the caller:

struct Codes *c = malloc(sizeof(struct Codes)+as*sizeof(int));
c->as = as;
for (int i = 0 ; i != as ; i++) {
    c->a[i] = i+1;
}
return c;

Change your function to return a pointer; make sure the caller frees the result.

Comments