在c中输入堆栈数据

Input to stack data in c

这个程序的目的是通过用户输入填充堆栈,并在每次输入新数据后显示栈顶的当前值和那个"top"变量的编号。但看起来我的程序没有按预期工作。当我 运行 程序 "your data" 和 "current stack size" 总是 0。我做错了什么吗?

#include <stdio.h>
#include <stdlib.h>
#define size 5

typedef struct stacktype
{
    double arr[size];
    int top;
} stack;

/*  prototype function */
void push(double elmt,stack c);

/*main program*/
int main(void)
{

char a;
double b;
stack c;

c.top=0;
printf("will you insert a data  (Y/N) ?\n");
scanf("%c",&a);
while (a=='Y'){

    printf("insert your data :\n");
    scanf("%lf",&b);
    push (b,c);
    printf("your data is : %.2f",c.arr[c.top]);
    printf("current stack size : %d",c.top);

    if(c.top!=size){
        printf("will you insert a data (Y/N) ?\n");
        scanf("%s",&a);
    }
}
return 0;
}

/* Implementation */
void push(double elmt, stack c)
{
   if(c.top!=size) {
        c.top = c.top + 1;
        c.arr[c.top] = elmt;
   }
   else {
        printf("Stack is full\n");
   }
}

您需要通过引用函数 push() 来传递堆栈变量 C。只有这样,在 push() 函数内部所做的更改才会反映到 main() 函数中的堆栈变量 c。

此外,c.top最初应该等于-1,因为在函数push()中,你是第一个递增堆栈变量的顶部数据成员,然后将数据存储到堆栈变量的数组中。这样,第一个元素将存储在 0.

/*  prototype function */
void push(double elmt,stack *c);

/*main program*/
int main(void)
{

    char a;
    double b;
    stack c;

    c.top=-1;
    printf("will you insert a data  (Y/N) ?\n");
    scanf("%c",&a);
    while (a=='Y'){

    printf("insert your data :\n");
    scanf("%lf",&b);
    push (b,&c);
    printf("your data is : %.2f",c.arr[c.top]);
    printf("current stack size : %d",c.top);

    if(c.top!=size){
        printf("will you insert a data (Y/N) ?\n");
        scanf("%s",&a);
   }
   }
    return 0;
}

/* Implementation */
void push(double elmt, stack *c)
{
    if(c->top!=size) {
        c->top = c->top + 1;
        c->arr[c->top] = elmt;
    }
    else {
         printf("Stack is full\n");
    }
}

像这样将参数传递给函数 'push()' 和它们的引用..

#include <stdio.h>
#include <stdlib.h>
#define size 5

typedef struct stacktype
{
    double arr[size];
    int top;
} stack;

/*  prototype function */
void push(double elmt,stack *p_c);

/*main program*/
int main(void)
{

    char a;
    double b;
    stack c;

    c.top=0;
    printf("will you insert a data  (Y/N) ?\n");
    scanf("%c",&a);
    while (a=='Y'){
        printf("insert your data :\n");
        scanf("%lf",&b);
        push(b,&c); // Address of c
        printf("your data is : %.2f",c.arr[c.top]);
        printf("current stack size : %d",c.top);

        if(c.top!=size){
            printf("will you insert a data(Y/N) ?\n");
            scanf("%s",&a);
        }
    }
    return 0;
}

/* Implementation */
void push(double elmt, stack *p_c)
{
    if(p_c->top!=size) {
        p_c->top = p_c->top + 1;
        p_c->arr[p_c->top] = elmt;
    }
    else {
        printf("Stack is full\n");
    }
}