以单个字符作为元素进行堆叠
Stack with single characters as elements
所以这里是创建和打印堆栈的代码,它的每个元素都是一个字符:
#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);
后尝试了您的代码,它可以工作。
在此之前,我有分段错误。
相关文章:
- 为什么平均打印数组元素比打印单个对象慢C++?
- C++:带有大括号初始化列表的函数调用表达式 - 标准是否规定在单个元素列表的微不足道的情况下忽略大括号?
- 如何在 c++ 中将整个数组初始化为类构造函数中的单个元素
- 删除二叉搜索树 (C++) 中的单个元素
- Leetcode 540 上的运行时错误.排序数组中的单个元素
- 使用一个内存集数组和单个堆栈在 O(n) 中查找数组的下一个更大元素
- 尝试从列表中随机选取单个元素并将其显示为C++
- 如何计算单个元素在向量<float>中所有元素之和中的百分比
- 我如何处理数组的单个元素
- 删除两个相邻的元素并用矢量中的单个元素替换它们
- 是否可以在C STL中获得集合的单个元素
- 从2D数组C 中删除单个元素
- 连续单个元素的敏感变量
- 在动态数组C 中删除单个元素
- 在C++中,如何在没有新元素且不单独声明单个元素的情况下创建"std::initializer_list<base *>"?
- 如何在多维数组中搜索单个行,然后对某些行中的每个单个元素执行计算
- 为什么数组(字符串类型)的大小是 24 字节,带有单个空格元素
- 移动单个矢量元素上的语义
- 如何在单个向量中查找匹配的元素
- 在什么基础上,由单个元素组成的参数包的折叠表达式被转换为未加括号的表达式