5

I'm trying to create an array of structs (of arrays) and am a bit unsure of the malloc required. First I define my struct,

typedef struct {

     char *str1, *str2, *str3, *str4;

 } player;

Then in main I need to initialize the structure, and malloc the strings inside of it,

player1 player; 
player1.str1 = malloc(100);
// and the rest

But this is just for one structure. How do I malloc an array of these structures? Do I need to have a for loop and create N instances of the struct?

I'm guessing there's a line that's something like

playerArray* = malloc(N * sizeof(player)) 

The end goal is to have something I can access using, say,

printf("%s\n", playerArray[i].str1)

After I've read stuff into it. Thanks.

1
  • Yup, you would need to loop, once you malloc the array, to malloc the strings. Commented Oct 17, 2013 at 10:11

1 Answer 1

6

Yes, you need to loop and allocate the strings for each instance of the struct. I suggest you create a function that looks something like this:

#define PLAYER_STR_LENGTH 100

typedef struct {
    char* str1, str2, str3;
    // ...
} player;

player* create_player() {
    player* p = malloc(sizeof(player));
    if (p == NULL) { 
        // out of memory, exit 
    }
    p->str1 = malloc(PLAYER_STR_LENGTH);
    if (p->str1 == NULL) { 
        // out of memory, exit 
    }
    // allocate more stuff...

    return p;
}

It is also a good idea to make a matching function free_player to clean up afterwards. You could also pass parameters to the create_player() function if you want to set values at the time of allocation.

To make an array of players, simply create an array of player pointers and then loop over it and allocate each player struct like so:

player** players = malloc(N * sizeof(player*));
for(int n = 0; n < N; n++)
    players[n] = create_player();
Sign up to request clarification or add additional context in comments.

1 Comment

Of course, I just used the number from his code. I'll my answer :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.