堆栈数组在C中的实现-理解通过引用



所以这是一个非常简单的堆栈实现(它是一个只包含基本推送pop函数的数组(。我试图理解为什么在将值推送到数组后,我的索引没有改变。我最初将itop变量定位在main中,称为"int itop=0",但由于itop值保持在0,我认为这可能是一个传递引用的问题,其中C获取值的副本,实际上不会更改传入的值本身。所以我想,好吧,我会在顶部设置一个静态int(我知道这不是最佳实践,因为线程行为不安全…(,但它仍然不起作用。

有人指出我理解这个基本概念吗?谢谢

#include <stdio.h>
void push(int a[], int, int);
int pop(int a[], int);
static int itop = 0;
int main(void){
int stack[100];
push(stack, itop, 1);
push(stack, itop, 2);
printf("index is %dn", itop);
int p1 = pop(stack, itop);
printf("index is %dn", itop);
int p2 = pop(stack, itop);
int p3 = pop(stack, itop);
printf("popped elements: %d %d %dn", p1, p2, p3);
return 0;
}
void push(int a[], int ind, int elem){
a[ind++] = elem;
}
int pop(int a[], int ind){
if (ind < 0){
return -1;
}
else {
return a[ind--];
}
}

您没有通过引用传递变量itop。你是在按价值传递。这两个函数都处理变量itop的副本,因此更改副本不会影响原始对象。

在C中通过引用传递意味着通过指针间接传递对象。

此外,函数pop在这些语句中存在错误

if (ind < 0){
^^^^^^^

return a[ind--];
^^^^^

功能可以通过以下方式声明和定义

void push(int a[], int *ind, int elem){
a[( *ind )++] = elem;
}
int pop(int a[], int *ind){
if (*ind == 0){
return -1;
}
else {
return a[--*ind];
}
}

请注意,通常情况下,函数pop有一个缺点,即不允许在堆栈中存储-1,因为函数返回的值-1不明确,可能意味着错误或堆栈的实际元素。

该功能可以通过以下方式定义

int pop( int a[], int *ind, int *value )
{
int error = *ind == 0 ? -1 : 0;
if ( error == 0 )
{
*value = a[--*ind];
}
return error;
}

在C中,参数是通过值传递的。因此这是错误的:

void push(int a[], int ind, int elem){
a[ind++] = elem;   // ind is a local variable here 
// modifying it won't have any effect outside
// the push function
}
...
push(foo, bar, elem);    // bar won't be modified

你想要这个:

void push(int a[], int *ind, int elem){
a[(*ind)++] = elem;
}
...
push(foo, &bar, elem);   // you pass a pointer to bar
// and bar will be modified

pop需要应用相同的原理。

这是最基本的C知识。

最新更新