C中的堆栈数组实现-理解按引用传递

问题描述 投票:0回答:1

因此,这是一个非常简单的堆栈实现(它的数组仅具有准系统推送弹出功能)。我试图理解为什么将值推入数组后索引没有改变。我最初将itop变量放置在main中为“ int itop = 0”,但是由于itop值保持为0,我认为这可能是传递引用的问题,其中C取值的一个副本,而“ t实际上会更改传入的值本身。因此,我想可以将其设置为顶部的静态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 %d\n", itop);
        int p1 = pop(stack, itop);
        printf("index is %d\n", itop);
        int p2 = pop(stack, itop);
        int p3 = pop(stack, itop);
        printf("popped elements: %d %d %d\n", 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--];
        }
}
c stack pass-by-reference
1个回答
0
投票

In 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知识。

© www.soinside.com 2019 - 2024. All rights reserved.