简体   繁体   English

C malloc字符串结构数组

[英]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. 我正在尝试创建一个结构数组(数组),并且我不太确定所需的malloc。 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, 然后在main中我需要初始化结构,并将malloc内部的字符串,

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? 我如何malloc这些结构的数组? Do I need to have a for loop and create N instances of the struct? 我是否需要一个for循环并创建结构的N个实例?

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. 最后制作一个匹配函数free_player来清理它也是一个好主意。 You could also pass parameters to the create_player() function if you want to set values at the time of allocation. 如果要在分配时设置值,也可以将参数传递给create_player()函数。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM