user2593573
user2593573

Reputation:

Array of structs initialized by function

What I am trying to do is create an array of structs, and initialize it through a function however I am getting a few errors,

lab2.c:20:2: error: declaration of anonymous struct must be a definition
    struct *person users[] = userInput();
    ^
lab2.c:20:2: warning: declaration does not declare anything[-Wmissing-declarations]
    struct *person users[] = userInput();
    ^~~~~~
lab2.c:24:1: error: declaration of anonymous struct must be a definition
    struct * userInput() {
    ^
lab2.c:48:2: error: expected identifier or '('
    }
    ^
1 warning and 3 errors generated.

Below is my code, in condensed version, if more is needed let me know, I'm pretty new to C so I'm guessing this is an obvious mistake on my part.

int main() {
    struct person users = userInput();
    return 0;
}

struct * userInput() {
     struct person users[30];
     ...do stuff to struct here...
     return *users;
}

Upvotes: 1

Views: 1666

Answers (2)

Sodved
Sodved

Reputation: 8588

OK, there are a number of things wrong with your code. Ignoring the syntactical stuff when you do something like:

struct person users[30]

That memory is temporary and freed when the function returns. Most likely to give you an segmentation fault or corrupt data. You need something like:

#include <stdlib.h>

typedef struct { char name[30]; int age; char gender; } person;

person* userInput();

int main() {
    person* users = userInput();
    return 0;
}

person* userInput() {
    person* users = malloc( 30 * sizeof(person) );
    /* Init stuff here */
    return users;
}

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726559

When declaring a pointer to a tagged struct, the asterisk follows the tag, not the keyword struct. To declare a dynamically allocated array, use an asterisk without square brackets:

struct person *users = userInput();

Returning a pointer to a local variable is undefined behavior:

struct person users[30];
// This is wrong
return *users;

Use dynamically allocated memory instead:

struct person *users = malloc(sizeof(struct user) * 30);

You will need to free it in the caller after you are done with the data.

Upvotes: 2

Related Questions