简体   繁体   English

用内部数组分配结构的数组

[英]Allocating array of struct with array inside

I want to read users input combined of strings and numbers, like this: 我想读取用户输入的字符串和数字,如下所示:

50:string one
25:string two blablabla
...

I don't know how many of the lines the input will have and I also don't know maximum length of the strings. 我不知道输入将有多少行,我也不知道字符串的最大长度。

So I created 所以我创造了

typdedef struct line
{ 
    int a
    char *string
} line;

Then an array of this sturct 然后是这个坚固的阵列

line *Array = NULL;

Now I have a cycle, that reads one line and parses it to temporaryString and temporaryA. 现在,我有一个循环,该循环读取一行并将其解析为临时字符串和临时A。 How can I realloc the Array to copy these into the array? 我如何重新分配数组以将它们复制到数组中?

There are two valid options to do what you want: 有两个有效的选项可以执行您想要的操作:

1) use the realloc() function; 1)使用realloc()函数; it's like malloc and calloc but you can realloc your memory, as the name can advise; 就像malloc和calloc一样,但是您可以根据名称建议重新分配内存;

2) use a linked list; 2)使用链表;

The second is more complex than the first one, but is also really valid. 第二个比第一个更复杂,但确实有效。 In your case, a simple linked list could have the form: 在您的情况下,一个简单的链表可以采用以下形式:

typdedef struct line
{ 
    int a;
    char *string;
    line *next;
    //line *prev;

} line;

Everytime you add a node, you have to alloc a struct line with your new data, set next pointer to NULL or to itself, it's the same, and set the previous next pointer to the new data you created. 每次添加节点时,都必须为新数据分配结构行,将下一个指针设置为NULL或将其自身设置为NULL,相同,然后将上一个下一个指针设置为创建的新数据。 That's a simpy method to do manually a realloc. 这是一个手动完成重新分配的简单方法。 The prev pointer is needed only if you need to go from the last item to the first; 只有当您需要从最后一项转到第一项时,才需要prev指针。 if you don't need this feature, just save the root pointer (the first one) and use only next pointer. 如果不需要此功能,只需保存根指针(第一个),然后仅使用下一个指针。

You could something like this (pseudo code). 您可能会这样(伪代码)。

idx = 0;

while (input = read()) {
    temporaryString, temporaryA = parse(input);
    Array = realloc(Array, (idx + 1)*sizeof(line));
    Array[idx].a = temporaryA;
    Array[idx].string = malloc(strlen(temporaryString) + 1);
    strcpy(Array[idx].string, temporaryString);
    idx++;
}

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

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