【发布时间】:2015-07-20 17:28:53
【问题描述】:
我对下面的代码感到困惑。为什么输入会覆盖堆栈中的元素。
例如我先输入“abc” 那么堆栈将是“123” 但是当我输入另一个字符串时,让我们说“234” 堆栈将为“234”“234”
但是当我使用 int 数据类型而不是 char 作为输入时,没有错误。
谢谢!
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct node{
char* info;
struct node *ptr;
}*top,*top1,*temp;
int count = 0;
/* Push data into stack */
void pushy(char* data){
if (top == NULL)
{
top =(struct node *)malloc(1*sizeof(struct node));
top->ptr = NULL;
strcpy(top->info, data);
}
else
{
temp =(struct node *)malloc(1*sizeof(struct node));
temp->ptr = top;
strcpy(temp->info, data);
top = temp;
}
count++;
}
/* Display stack elements */
void display(){
top1 = top;
if (top1 == NULL)
{
printf("Stack is empty");
return;
}
while (top1 != NULL)
{
printf("%s ", top1->info);
top1 = top1->ptr;
}
}
/* Pop Operation on stack */
void pop(){
top1 = top;
if (top1 == NULL)
{
printf("\n Error : Trying to pop from empty stack");
return;
}
else
top1 = top1->ptr;
printf("\n Popped value : %s", top->info);
free(top);
top = top1;
count--;
}
/* Return top element */
char* topelement(){
return(top->info);
}
int main()
{
int ch=0;
printf("\n 1 - Push");
printf("\n 2 - Pop");
printf("\n 3 - Top");
printf("\n 4 - Display");
printf("\n 5 - Exit");
top = NULL;
while (1)
{
char no[10]={NULL};
char* e;
printf("\n Enter choice : ");
scanf("%d", &ch);
if(ch==1){
printf("Enter data : ");
scanf("\n\n%s", &no);
pushy(no);
}
else if(ch==2){
pop();
}
else if(ch==3){
if (top == NULL)
printf("No elements in stack");
else
{
e = topelement();
printf("\n Top element : %d", e);
}
}
else if(ch==4)
display();
else if(ch==5)
exit(0);
else
printf("Invalid");
}
}
【问题讨论】:
-
快速浏览:您没有为
struct node的成员info分配内存,因此可能所有info都指向同一个内存位置。通常你会遇到分段错误。将strcpy更改为strdup,以自动分配内存并创建字符串的副本。也不要忘记在pop函数中释放top->info之前的free(top)。 -
不要在 C 中转换
malloc。
标签: c linked-list stack