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

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

问题描述

出于学习目的,我正在用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.

我写了一个函数,它最初创建我的堆栈结构.函数的返回值是一个已经分配了内存的新结构体.在函数的返回值应为struct的函数中处理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实例:

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结构,您可以(读取:必须)使用 delete_stack()中的 free(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->复制内容.数据,释放 stack->数据并将其设置为新分配的数组:

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中使用malloc进行堆栈实现[BEGINNER]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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