在 c [BEGINNER] 中使用 malloc 实现堆栈 [英] stack implementation using malloc in c [BEGINNER]

查看:18
本文介绍了在 c [BEGINNER] 中使用 malloc 实现堆栈的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

出于学习目的,我在 c 中实现了一个堆栈及其函数.我添加了一些小的附加功能来第一次使用 malloc 并尝试正确理解它.

for learning purpose I'm implementing a stack with it's functions in c. I added some small additional functionality to use malloc the first time and try to understand it properly.

我写了一个函数,它最初是创建我的堆栈结构.该函数的返回值是一个已分配内存的新结构.在返回值应该是结构的函数中处理 malloc 异常的最佳方法是什么?也许我应该设计不同的功能?我知道 printf 没有做它的工作;)

I wrote a function which is initially creating my stack struct. The return value of the function is a new struct with an already allocate memory. What is the best way to handle a malloc exception in a function which return value should be a struct? Maybe should I design the function different? I'm aware that the printf is not doing it's job ;)

我的堆栈结构:

typedef struct Stack
{
    int count;
    int capacity;
    int *data;
} Stack;

创建堆栈实例:

Stack create_stack(int initialcapacity)
{
    Stack new_stack;
    new_stack.count = 0;
    new_stack.capacity = initialcapacity;

    if (!(new_stack.data = malloc(initialcapacity * sizeof(int))))
        printf("not enough memory!");

    return new_stack;
}

函数以堆栈的初始容量调用:

The function is called with the initial capacity of the stack:

Stack stack = create_stack(10);

第二个问题出现在我编写删除 Stack 实例的函数时.

A second question came up while I was writing a function to delete the Stack instance.

int delete_stack(Stack *stack)
{
    stack->count = 0;
    stack->capacity = 0;
    free(stack->data);
    stack->data = NULL;
    return 0;
}

我是否也可以删除结构实例本身?将值设置回 0 并将 int* 指向 NULL 感觉不完整.

Am I able to remove also the struct instance itself? It feels not complete to just set the values back to 0 and direct int* to NULL.

最后但同样重要的是,我对推送功能有疑问.另外在这里我添加了一些功能,允许我在堆栈已满时将其推送到堆栈上:

Last but not least, I have a question to my push function. Also here I added some functionality which allows me to push something on the stack while it is already full:

void push(int value, Stack *stack)
{   
    if (stack->count == stack->capacity)
    {   
        int *temp = malloc(stack->capacity * sizeof(int));

        int i;
        for (i = 0; i < stack->count; i++)
            temp[i] = stack->data[i];

        free(stack->data);
        stack->data = NULL;

        stack->data = malloc(stack->capacity * 2 * sizeof(int));

        for (i; i > -1; i--)
            stack->data[i] = temp[i];

        free(temp);
        temp = NULL;
        stack->data[stack->count] = value;
        stack->count++;
        stack->capacity = stack->capacity * 2;
    }
    else
    {
        stack->data[stack->count] = value;
        stack->count++;
    }
}

在分配两倍大小的新数组之前,是否有必要释放"较小的数组并将指针指向 NULL?

Is it necessary to "free" the smaller array and put the pointer to NULL before I allocate a new array double the size?

如果我的代码中有任何不必要或写得不正确的地方,请告诉我,我很感激任何让我变得更好的提示.

If there is anything from my code which is unnecessary or not written properly, please let me know, I'm grateful for any hint which makes me better.

干杯,我

推荐答案

我会用指针来做.也就是说,您的 create_stack() 将使用 malloc 分配一个新的 Stack 结构,然后将值设置为该结构并再次使用 malloc 为 Stack 分配空间->数据.像这样:

I would do it with pointers. That is, your create_stack() would allocate a new Stack struct using malloc, then set the values to the struct and usee malloc again to allocate space for the Stack->data. Like this:

Stack* create_stack(int initialcapacity) {
    Stack* new_stack = malloc(sizeof(Stack));

    if (new_stack == NULL)
        return NULL; // return null to tell the caller that we failed

    new_stack->count = 0;
    new_stack->capacity = initialcapacity;
    new_stack->data = malloc(initialcapacity * sizeof(int))

    if (new_stack->data == NULL)
    {
        free(new_stack);
        return NULL;
    }

    return new_stack;
}

这样,我们通过返回 NULL 处理" malloc 错误,因此调用者知道我们失败了.

With this, we "handle" a malloc error by returning NULL, so the caller knows we failed.

现在我们已经使用 malloc 来分配 Stack 结构体,您可以(阅读:必须)使用 free(stack); in delete_stack() 释放它占用的空间代码>.

Now that we have used malloc to allocate the Stack struct, you can (read: MUST) free the space taken by it using free(stack); in delete_stack().

push()中,不需要临时数组,也就是说,你可以直接分配一个更大的数组,把原来的stack->中的内容复制进去.data,释放 stack->data 并将其设置为新的 malloc 数组:

In push(), the temporary array is not needed, that is, you could just right away allocate a bigger array, copy the contents to it from the original stack->data, free stack->data and set it to the newly malloc'd array:

int *temp = malloc(stack->capacity * 2 * sizeof(int));
// TODO: what if malloc fails?

int i;
for (i = 0; i < stack->count; i++)
    temp[i] = stack->data[i];

free(stack->data);
stack->data = temp;

stack->data[stack->count] = value;
stack->count++;
stack->capacity = stack->capacity * 2;

这篇关于在 c [BEGINNER] 中使用 malloc 实现堆栈的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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