Pranshu Patel
Pranshu Patel

Reputation: 13

How do you return an array of structs from a function in C?

I'm trying to create an array of structs and fread file data in to the array inside a helper function. I keep getting incompatible pointer type errors when I compile the program. This is my current code:

 struct fentry *read_fentries(FILE *fp){
    fentry *files[MAXFILES];

    // EXTRACT FENTRIES AND FNODES FROM FILE
    if ((fread(files, sizeof(fentry), MAXFILES, fp)) == 0) {
        fprintf(stderr, "Error: could not read file entries\n");
        closefs(fp);
        exit(1);
    }
    return files;
}

Terminal Output

My main question is how can I create an array of structs of a pre-defined size (MAXFILES) and return it from a function so that I can access the struct array inside my main. Would I have to allocate memory using malloc?

Upvotes: 1

Views: 173

Answers (2)

Eraklon
Eraklon

Reputation: 4288

You have to allocate space for it with malloc for example, because as you see from the error you returning a pointer to a local address, which is a problem since once you exit this function the files array will be freed/non existent. So you returning pointer will point to an invalid memory location.

So do something like this:

struct fentry *files = malloc(MAXFILES * sizeof(fentry);

Also in this case do not forget to free the allocated memory with free(*ptr_to_array) when does not needed anymore.

Upvotes: 0

0___________
0___________

Reputation: 67546

you can also return be the value if you wrap the array.

#define MAXFILES 50

struct _fentry
{
    FILE *fp;
    int somedata[3];
    double anotherdata[10];
    /* ... */
};

struct fentry
{
    struct _fentry entries[MAXFILES];
};


struct fentry foo()
{
    struct fentry entries;

    /* .... */

    return entries;
}

Upvotes: 1

Related Questions