gpt4 book ai didi

C:堆栈元素被函数调用覆盖

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

我正在做一项学校作业,我遇到了 2 个问题。我必须用数组模拟堆栈。我目前的代码如下:

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

typedef struct {
int capacity;
int * array;
int size;
} stack_tt;
int pop(stack_tt * stack_p);
void push(stack_tt * stack_p, int value);
int top(stack_tt * stack_p);
stack_tt * newStack(void);
int empty(stack_tt * stack_p);

int main() {
stack_tt * myStack = newStack();
push(myStack, 123);
push(myStack, 99);
push(myStack, 4444);
while (!empty(myStack)) {
int value;
value = pop(myStack);
printf("popped: %d\n", value);
}
return 0; }

stack_tt * newStack(){
stack_tt * newS = malloc(sizeof(stack_tt) * 20);
(*newS).capacity = 1;
(*newS).size = 0;
return newS;
}

void push(stack_tt * stack_p, int value){
if ((*stack_p).size >= (*stack_p).capacity) {
(*stack_p).capacity*=2;
//realloc(stack_p, stack_p->capacity * sizeof(stack_tt));
}
(*stack_p).array = &value;
(*stack_p).size++;
}

int pop(stack_tt * stack_p){
(*stack_p).size--;
int fap = *(*stack_p).array;
return fap;
}

int empty(stack_tt * stack_p){
if ((*stack_p).size >= 1)
return 0;
return 1;
}

拳头的,当我打电话的时候 同时(!空(myStack))它将我数组中的值更改为 1。

其次,每当我尝试以下操作时,我都无法更改数组中的单个值: (*stack_p).array[0] = 值;它不知道在内存中的哪个位置查找。我希望有人能够帮助我:)

最佳答案

在我看来,代码存在一些问题。

让我们把push 函数放在你做的地方

(*stack_p).array = &value;

这将使array 结构成员指向本地 变量value,并且一旦函数返回该变量就不存在了使用杂散指针并使用该指针将导致未定义的行为

该代码的第二个问题是您的堆栈只会(非法)指向最后添加的元素。

您必须为 array 显式分配内存,并使用 capacity 来跟踪分配了多少内存。使用 size 作为压入和弹出分配数组的索引。有点像

stack_tt * newStack(){
stack_tt * newS = malloc(sizeof(stack_tt)); // Only allocate *one* structure
newS->capacity = 0; // Start with zero capacity
newS->size = 0;
newS->array = NULL;
return newS;
}

void push(stack_tt * stack_p, int value){
if (stack_p->size + 1 > stack_p->capacity){
// Increase capacity by ten elements
int new_capacity = stack_p->capacity + 10;
int * temp_array = realloc(stack_p->array, new_capacity * sizeof(int));
if (temp_srray == NULL)
return;

stack_p->capacity = new_capacity;
stack_p->array = temp_array;
}

stack_p->array[stack_p->size++] = value;
}

int pop(stack_tt * stack_p){
if (stack_p->size > 0)
return stack_p->array[--stack_p->size];
return 0;
}

int empty(stack_tt * stack_p){
return stack_p->size == 0;
}

关于C:堆栈元素被函数调用覆盖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37097470/

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