C中的结构内的指针指向的自由数组 [英] Free array pointed to by a pointer within a struct in C

查看:80
本文介绍了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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆