当您为内存分配空间时,您如何判断是否需要为其分配更多空间?是否有检查或者您可以对新内存进行检查以确保它正常? (为结构分配内存)。
因为我在想的是结构是一定数量的数据,即使我经常传递它,它应该永远不需要超过结构的大小正确吗?
答案 0 :(得分:3)
如果您只是使用简单的struct
,则随着时间的推移,您不需要为其分配更多内存。您只需创建struct
,使用它,并在需要时进行清理。如果您正在动态分配结构(即:with malloc
),那么您将测试您创建的指针结构的值,并查看它是否为NULL
。如果它是NULL
,则内存分配失败,您可以重试或放弃进一步的操作(即:在错误条件下退出)。
#include <stdio.h>
typedef struct myStruct {
int i;
char c;
} myStruct;
int main(void) {
// Static allocation, no cleanup required
myStruct staticStruct;
staticStruct.i = 0;
staticStruct.c = 'c';
// Dynamic allocation, requires cleanup
myStruct* dynamicStruct;
dynamicStruct = malloc(sizeof(myStruct));
if (dynamicStruct == NULL) {
printf("Memory allocation error!\n");
return (-1);
} else {
printf("Successfully allocated memory!\n");
}
dynamicStruct->i = 1;
dynamicStruct->c = 'd';
free(dynamicStruct); // Release allocated memory
dynamicStruct = NULL; // Somewhat common practise, though not 100% necessary
return 0;
}
现在,如果你需要创建一个动态分配的结构数组,并且你已经全部使用它们,并且需要更多,那么你可能最好采用一种稍微复杂的方法,比如一个动态分配的链表结构。一个很好的例子可以在下面的“参考文献”部分找到。另外,我已经包含了一个链接到我在C中的内存分配上回答的一个相关的问题。它有一些很好的例子,可能也有助于为你清理这个主题。
<强>参考强>
<http://www.thegeekstuff.com/2012/08/c-linked-list-example/>
<https://stackoverflow.com/questions/16021454/difference-between-declared-string-and-allocated-string>