【发布时间】:2015-08-11 10:06:18
【问题描述】:
作为分配的一部分,我目前正在将一个包含 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 是在头部定义的二维数组。
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);
}
谢谢,杰克
【问题讨论】:
-
如何为 struct Stack 分配内存?
-
您是为每次使用 push 分配不同的 locArr 还是重复使用同一个?