displayStack函数打印随机字母

时间:2019-05-20 07:26:55

标签: c data-structures

我正在尝试使用数组创建堆栈。我已经完成了所有必要的功能,并且控制台中没有错误。

printfdisplayStack()的输出是

ê    @² ` Ç      i   i     q @╨ @. ` Ç   x  

我该如何解决?

我的代码是:

#include <stdio.h>
#include <stdlib.h>


struct Stack {

    int top;
    char  array[];// Array for stack which will store the operators from infx

};

void createStack(struct Stack st){
st.top=-1;
}

void push(struct Stack st,char ch)
{
st.top++;
st.array[st.top]=ch;
}
void displayStack(struct Stack st){
    int i;
    for (i=st.top;i>=0;i--){
        printf("%c\n",st.array[i]);
    }
}
char pop(struct Stack st){
    char x='x';
    if(st.top<0){
        printf("Stack UnderFlow\n");
    }else{
        x= st.array[st.top];
        st.top--;
    }
    return x;
}

int main()
{
struct Stack st;
createStack(st);
push(st,'x');
push(st,'x');
push(st,'x');
push(st,'x');
push(st,'x');
push(st,'x');

displayStack(st);
pop(st);
    return 0;
}

1 个答案:

答案 0 :(得分:1)

这里:

struct Stack {
    int top;
    char  array[];
};

array可以用作flexible array member,但是您需要malloc的大小为struct +要在数组中使用的元素数,即:

data = malloc(sizeof(*data) + nelements);

否则,编译器将不知道要与数组关联多少个元素

相关问题