C中的简单堆栈结构程序返回“(null)”而不是peek()值

时间:2018-03-25 15:53:45

标签: c struct

我是C的新手,我想编写一个简单的堆栈程序来训练自己一点点,我认为这很简单,但我遇到了很多问题...... 当我从Windows的命令行运行它时,屏幕上的所有内容都是(null),当我希望它显示的是a.list[0]中的值应该等于123时。 这是我的代码:

#include <stdio.h>

struct stack {
    int list[256];
    int lastelement;
};

void push(struct stack stack, int newelement) {
    stack.list[stack.lastelement] = newelement;
    stack.lastelement++;
};

int peek(struct stack stack) {
    return stack.list[stack.lastelement];
};

int main(int argc, char *argv[]) {

    struct stack a = {0, 0};

    push(a, 123);

    int result = peek(a);

    printf("%s\n", result);

    return 0;
}

1 个答案:

答案 0 :(得分:0)

如果将结构作为值传递给堆栈,则任何更改都不会传播。 您也可以访问列表中的初始化元素。打印十进制值为"%d""%s"用于字符串。

#include <stdio.h>

struct stack {
    int list[256];
    int lastelement;
};

void push(struct stack *stack, int newelement) {

    stack->list[stack->lastelement] = newelement;
    stack->lastelement++;
};

int peek(struct stack *stack) {
    return stack->list[(stack->lastelement)-1];
};

int main(int argc, char *argv[]) {

    struct stack a = {0, 0};

    push(&a, 123);
    push(&a, 456);

    int result = peek(&a);

    printf("%d\n", result);

    return 0;
}

输出:

456