C中的结构内的指针指向的自由数组 [英] Free array pointed to by a pointer within a struct in C
问题描述
我有一个在动态数组中实现的堆栈.以下是我的一些功能.当我调用stk_reset函数时,似乎堆栈没有完全释放.
I have a stack implemented in dynamic array. Below are some of my functions. When I call stk_reset function, it seems that the stack is not freed completely.
这是我的结构.要求我必须在结构内部有一个指向动态数组的指针
Here is my struct. It is a requirement that I have to have a pointer inside struct pointing to the dynamic array
typedef struct stack {
char *items;
int arrSize;
int top;
} StackStruct;
void stack_create(StackStruct *s) {
char *arr = malloc(sizeof(char)*2);
if (arr == NULL) {
printf("Insufficient memory to initialize stack.\n");
return;
}
s->arrSize = 2;
s->items = arr;
s->top = -1;
}
如何释放分配堆栈的数组的每个元素?我将此语句free((s-> items)++)与for循环一起使用,但没有用.
How do I deallocate each element of the array holding the stack? I used this statement free((s->items)++) with a for loop, but it did not work.
void stk_reset(StackStruct *s) {
int i;
for (i = 0; i <= s->arrSize; i++)
free((s->items)++);
free(s->items);
s->items = NULL;
s->top = -1;
s->arrSize = 0;
}
推荐答案
您希望对malloc
的每次调用都对(c0>)进行一(1)次调用.在这里,您只分配了一个有两个字符的空间的项目.要free
,它非常简单.这就是所谓的安全"发布(或免费).
You want one (1) call to free
per call to malloc
. Here you've only allocated one item with room for two characters. To free
it, it's pretty straight-forward. Here is what is called a "Safe" release (or free).
if (s->items != NULL) {
free(s->items);
s->items = NULL; // Reset to be safe.
}
尽管要使用此功能,但在尝试使用它之前,需要确保将其值初始化为NULL:s->items = NULL;
.
Though to use this, you will need to make sure you initialize your value to NULL before you try to use it: s->items = NULL;
.
不需要其他free
调用,并且当您只有一个malloc
时肯定不会循环.
No other free
calls are required, and certainly not in a loop when you only had one malloc
.
这篇关于C中的结构内的指针指向的自由数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!