我知道如何创建具有预定义大小的结构数组。但是,有没有办法创建动态结构数组,使数组变得更大?
例如:
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 我会得到一个错误,这正是我想要的。那么 free 函数是否不起作用,至少在我的编译器上是这样?我正在使用DevC?
谢谢,我现在明白了,因为:
FirstName 是一个指向 char 数组的指针,该数组没有被 malloc 分配,只有指针被分配,并且在调用 free 后,它不会擦除内存,它只是将其标记为在堆上可用以结束稍后写。 - 马特·史密斯
Update
我正在尝试模块化并将结构数组的创建放入函数中,但似乎没有任何效果。我正在尝试一些非常简单的事情,但我不知道还能做什么。它与以前一样,只是另一个函数 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;
}//
这个简单的测试代码崩溃了,我不知道为什么。错误在哪里?