推送功能期间堆栈结构更新不正确

Stack Struct Updating Incorrectly During push Function

作为作业的一部分,我目前正在将一个包含 2 个整数的数组压入堆栈式结构。每次推送时,它都应该将新的整数数组添加到堆栈的顶部。相反,它添加一个,并更改整个堆栈以匹配新数组。

堆栈定义

    typedef struct Stack
{
    int **items;
    int size;
} Stack;

推送和打印功能

void push(Stack* s, int* item)
{
    // check to make sure there is space on the stack
    if(s->size >= CAPACITY)
    {
        // if the stack is full print full stack
        printf("FULL_STACK");
        return;
    }
    // if stack is not full add the ITEM to the top of the stack
    s->items[s->size] = item;
    s->size++;
    printf("the size is: %d \n", s-> size);
}
void print_stack(Stack* s)
{
    int i;
// Iterate through the stack to print the contents of it.
    for(i = 0; i < s->size; i++)
    {
        printf("%d; %d; \n",s->items[i][0],s->items[i][1]);
    }
    printf("---------------\n");
}

两种方法的调用。 locArr 是在 header.

中定义的二维数组
locArr[0] = l->xloc;
locArr[1] = l->yloc;
push(s, locArr);
print_stack(s);

运行这个

的结果
the size is:
10, 1 ;
10, 1 ;
10, 1 ;

它应该在的地方

  the size is:
    10, 1 ;
    10, 2 ;
    11, 2 ;

编辑; 代码已修改为在结构 "l" 中使用数组。不幸的是,这仍然得到相同的回应。 DKO 关于输入指针而不是它的值的理论是有道理的,但我不确定用于检索所述值的代码。

修改后的方法。

push(s, l->loc);
print_stack(s);

}

谢谢,杰克

似乎正在从下面的代码将本地数组(也许在堆栈上?)传递给 push()。

locArr[0] = l->xloc;
locArr[1] = l->yloc;
push(s, locArr);

但是 push() 在项目中存储指向本地堆栈的指针,而不是本地数组的副本,因此它可能在堆栈数组中的每个位置存储相同的指针。因此,如果相同的指针存储在堆栈项数组的每个位置,则堆栈的大小会增加,但在所有情况下始终打印出最新添加的项。

为了修复,我会 malloc 每个数组,对其进行初始化,并将其作为参数传递给推送。 pop 将 return 数组,您将在使用其数据后释放它。

int* array = (int*) malloc(2*sizeof(int));
if (array == NULL) abort();
array[0] = l->xloc;
array[1] = l->yloc;
push(s, array);

array = pop(s);
/* Use array */
free(array);