gpt4 book ai didi

C、全局变量的改变不保留在函数之外

转载 作者:行者123 更新时间:2023-11-30 20:29:07 24 4
gpt4 key购买 nike

在 pop() 函数中,我试图更改 Last 全局变量的值。它在 push(n) 函数中工作正常,而在 pop() 函数中,它在函数内部更改它(通过打印验证它),但在离开该方法后它会重置为前一个值。我无法理解它。

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

int *Stack;
int Last = -1;

void make_empty( void ){
free(Stack);
Last = -1;
Stack = NULL;
//Stack = malloc(4);
return;
}

int is_empty( void ){
if (Last == -1)
return 1;
return 0;
}

int top( void ){
if (is_empty()) {
printf("La pila è vuota");
}
return Stack[Last];
}

int pop( void ){
if (is_empty()) {
printf("La pila è vuota");
return 0;
}
int temp = Stack[Last];
printf("last: %d\n", Last);
Stack = realloc(Stack, (--Last+1)*sizeof(int));
printf("last: %d\n", Last);
return temp;
}

void push( int n ){
Stack = realloc(Stack, (++Last+1)*sizeof(int));
Stack[Last] = n;
return;
}

void print_stack( void ){
printf("last: %d\n", Last);
for (int c=0; c<=Last; c++)
printf("%d ", Stack[c]);
printf("\n");
}

最佳答案

您没有为堆栈分配足够的空间。

开始时Last是-1。然后将一个元素压入堆栈并分配空间:

Stack = realloc(Stack, ++Last*sizeof(int));

增量后,Last 为 0。因此您要分配 0*sizeof(int) == 0 字节。然后,您写入不存在的 Stack[Last] 。这会调用 undefined behavior ,在您的情况下,这会导致变量在您不期望的情况下发生变化。

由于 Last 包含最后一个有效索引,因此您需要向其添加 1 以获得要分配的正确元素数:

Stack = realloc(Stack, (++Last + 1)*sizeof(int));

你在弹出时犯了类似的错误:

Stack = realloc(Stack, --Last*sizeof(int));

您还需要在此处添加 1:

Stack = realloc(Stack, (--Last + 1)*sizeof(int));

关于C、全局变量的改变不保留在函数之外,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58976726/

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