简体   繁体   中英

C malloc array of structs of strings

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.

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();

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