我知道如何创建一个结构数组但具有预定义的大小。但是,有没有办法创建一个动态的结构数组,使数组变得更大?
例如:
typedef struct
{
char *str;
} words;
main()
{
words x[100]; // I do not want to use this, I want to dynamic increase the size of the array as data comes in.
}
这可能吗?
我研究过这个:words* array = (words*)malloc(sizeof(words) * 100);
我想摆脱 100 并在数据进入时存储数据。因此,如果有 76 个数据字段进入,我想存储 76 而不是 100。我假设我不知道有多少数据即将到来进入我的程序。在我上面定义的结构中,我可以将第一个“索引”创建为:
words* array = (words*)malloc(sizeof(words));
但是我想在之后动态地将元素添加到数组中。我希望我足够清楚地描述了问题区域。主要挑战是动态添加第二个字段,至少这是目前的挑战。
但是,我取得了一些进展:
typedef struct {
char *str;
} words;
// Allocate first string.
words x = (words) malloc(sizeof(words));
x[0].str = "john";
// Allocate second string.
x=(words*) realloc(x, sizeof(words));
x[1].FirstName = "bob";
// printf second string.
printf("%s", x[1].str); --> This is working, it's printing out bob.
free(x); // Free up memory.
printf("%s", x[1].str); --> Not working since its still printing out BOB even though I freed up memory. What is wrong?
我做了一些错误检查,这就是我发现的。如果在我为 x 释放内存之后,我添加以下内容:
x=NULL;
那么如果我尝试打印 x 我会得到一个我想要的错误。那么是不是免费功能不起作用,至少在我的编译器上?我正在使用开发人员??
谢谢,我现在明白了,原因是:
FirstName 是一个指向 char 数组的指针,它没有被 malloc 分配,只有指针被分配,在你调用 free 之后,它不会擦除内存,它只是将它标记为在堆上可用结束后来写的。- 马特·史密斯
更新
我正在尝试模块化并将我的结构数组的创建放在一个函数中,但似乎没有任何效果。我正在尝试一些非常简单的事情,我不知道还能做什么。它与以前的思路相同,只是另一个函数 loaddata 正在加载数据,并且在我需要进行一些打印的方法之外。我怎样才能让它工作?我的代码如下:
# include <stdio.h>
# include <stdlib.h>
# include <string.h>
# include <ctype.h>
typedef struct
{
char *str1;
char *str2;
} words;
void LoadData(words *, int *);
main()
{
words *x;
int num;
LoadData(&x, &num);
printf("%s %s", x[0].str1, x[0].str2);
printf("%s %s", x[1].str1, x[1].str2);
getch();
}//
void LoadData(words *x, int * num)
{
x = (words*) malloc(sizeof(words));
x[0].str1 = "johnnie\0";
x[0].str2 = "krapson\0";
x = (words*) realloc(x, sizeof(words)*2);
x[1].str1 = "bob\0";
x[1].str2 = "marley\0";
*num=*num+1;
}//
这个简单的测试代码崩溃了,我不知道为什么。错误在哪里?