以单个字符作为元素进行堆叠

Stack with single characters as elements

本文关键字:元素 单个 字符      更新时间:2023-10-16

所以这里是创建和打印堆栈的代码,它的每个元素都是一个字符:

#define max 100
struct stack
{
int top;
char data[max];
};
void initialize (stack &s)
{
    s.top=0; 
}
void push(stack &s, char x) 
{
    s.data[s.top]=x;
    s.top ++;
}
void create (stack &s, int n) //n is the number of elements
{
    char x;
    for(int i=0;i<n;i++)
    {
        printf("Enter the char to push in: ");
        scanf(" %c",&x);
        push(s,x);
    }
}
void print (stack s)
{
    int a;
    printf("nStack:n");
    for(a=s.top-1;a>=0;a--)
    {
        printf("  %c",s.data[a]);
    }
}
int main()
{
    int n;
    stack s;
    printf("Enter the number of stack elements:");
    scanf("%d",&n);
    create(s,n);
    print(s);
}

现在我遇到的问题是上面的代码运行良好,我可以创建一个堆栈并将单个字符推送到其中。但是当它将元素打印到屏幕上时,结果末尾总是有这些垃圾字符:@ ' 1

例如:如果我输入"C o o l!",那么它会打印"!l o o C @ ' 1"

我该如何解决它?

您不会在 create() 之前调用 initialize(),这意味着stack.top未初始化的,这会在访问时调用未定义的行为。

将您的主函数更改为:

stack s;
initialize(s);
...
create(s,n);

您没有初始化堆栈。试试这个:

int main()
{
    int n;
    stack s;
    printf("Enter the number of stack elements:");
    scanf("%d",&n);
    initialize(s);
    create(s,n);
    print(s);
    return 0;
}

我在create(s,n);之前添加initialize(s);后尝试了您的代码,它可以工作。

在此之前,我有分段错误。