gpt4 book ai didi

c - 将一个指向struct的指针和一个int传递给C中的函数以实现堆栈

转载 作者:太空宇宙 更新时间:2023-11-04 06:49:30 26 4
gpt4 key购买 nike

我试图在 C 中实现一个堆栈。我只实现了将包含一个数组的结构,并且当前只包含数组的大小和添加到堆栈的最后一项的位置

这是给我带来一些麻烦的部分实现。

在堆栈中

#include <stdlib.h>
#include <stdbool.h>

typedef struct Stack
{
int max_size;
int top;
// int *contents;
} Stack;

Stack *stack_create(int n);
bool stack_is_empty(Stack *stack);
bool stack_is_full(Stack *stack);
void stack_push(Stack *stack, int value);

在 stack.c 中:

#include <stdio.h>
#ifndef STACK_H
#include "stack.h"
#endif

Stack *stack_create(int n)
{
Stack stack;
Stack *s = &stack;
s->max_size = n;
s->top = 0;
// s->contents = (int *)malloc(sizeof(int) * n);
return s;
}


bool stack_is_empty(Stack *stack)
{
if (stack->top == 0)
{
return true;
}
return false;
}

bool stack_is_full(Stack *stack)
{
if (stack->top == stack->max_size)
{
return true;
}
return false;
}

void stack_push(Stack *stack, int value)
{

if (!stack_is_full(stack))
{
printf("max_size: %d\n", stack->max_size);
printf("top: %d (%p)\n", stack->top++, &stack->top);
printf("value: %d (%p)\n", value, &value);
}
else
{
printf("Can't push. max_size==%d reached.\n", stack- >max_size);
exit(EXIT_FAILURE);
}
}

在 main.c 中:

 #include <stdio.h>
#include <stdlib.h>
#include "stack.h"

#define SIZE 3

int main()
{
Stack *s = stack_create(SIZE);
printf("stack_is_empty: %d\n", stack_is_empty(s));
stack_push(s, 100);
printf("stack_is_empty: %d\n", stack_is_empty(s));
stack_push(s, 30);
printf("stack_is_empty: %d\n", stack_is_empty(s));
stack_push(s, 20);
printf("stack_is_empty: %d\n", stack_is_empty(s));

return 0;
}

main 产生以下输出:

stack_is_empty: 1
max_size: 3
top: 100 (0x7ffd5430dfb4)
value: 101 (0x7ffd5430dfb4)
stack_is_empty: 0
max_size: 3
top: 30 (0x7ffd5430dfb4)
value: 31 (0x7ffd5430dfb4)
stack_is_empty: 0
max_size: 3
top: 20 (0x7ffd5430dfb4)
value: 21 (0x7ffd5430dfb4)
stack_is_empty: 0

为什么value的地址和stack->top的地址一样?

最佳答案

问题 1:您在 stack_create 函数中为本地堆栈分配内存。一旦函数超出范围,内存将被释放。因此,您将有一个悬空指针。

问题 2:无论 'n' 的值如何,您只为一个实例分配内存

typedef struct Stack
{
int max_size;
int *contents;
int top;
// int *contents;
} Stack;

Stack *stack_create(int n) {
Stack *s;
s = (Stack *)malloc(sizeof(Stack));
s->contents = (int *)malloc(sizeof(int) * n);
s->max_size = n;
s->top = 0;
return s;
}

关于c - 将一个指向struct的指针和一个int传递给C中的函数以实现堆栈,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53460029/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com