【发布时间】:2020-03-07 06:32:58
【问题描述】:
我正在尝试使用 malloc 和 realloc 来保存一个结构数组。数组应该动态增长,大小应该每次增加 10 个结构元素。
结构:
typedef struct
{
unsigned char foreign_word_[100] = {0};
unsigned char native_word_[100] = {0};
} VocabularyCouple;
在我的 main 中,我使用 malloc 初始化数组:
VocabularyCouple* VocStruct = (VocabularyCouple*)malloc(sizeof(*VocStruct) * 10);
增加 struct-array 的大小似乎在 main 中可以正常工作...
VocabularyCouple* temp = (VocabularyCouple*)realloc(VocStruct, (sizeof(VocabularyCouple) * 20));
if (temp == NULL)
{
printf("ERROR: Out of Memory\n");
return 4;
}
else
{
VocStruct = temp;
free(temp);
temp = NULL;
}
但是,如果我将 realloc-part 放入这样的函数中:
uint8_t resizeVoc(uint32_t new_size, VocabularyCouple **VocStruct)
{
VocabularyCouple *temp = (VocabularyCouple*)realloc(*VocStruct, (sizeof(VocabularyCouple) * new_size));
...
}
我只能调用该函数一次。其他所有调用都会导致此错误:
HEAP[VocTest.exe]: Invalid address specified to RtlValidateHeap( 01300000, 01308500 )
除非我遗漏了什么,否则这应该与c - Realloc an array of Structs 的问题相同,但我就是无法让它工作。
感谢您的帮助!
【问题讨论】:
-
请不要在这里修复代码,如果需要,请发布一个新问题。
-
非常感谢,您解决了我的问题。我尝试设置
VocStruct = &temp而不是*VocStruct = temp;。 -
typedef struct { unsigned char foreign_word_[100] = {0}; unsigned char native_word_[100] = {0}; } VocabularyCouple;是什么语言?
标签: c arrays struct malloc realloc