我想实现一个使用数组的动态堆栈。用户输入他想要放入堆栈的单词的字母数。如果堆栈为空,则会创建一个块来保存用户传递到堆栈的信息。如果没有,那么堆栈被重新分配,以便它可以保存更多的信息块(单词)。然后用户输入他想要放入堆栈的单词(在打印堆栈索引的那一部分)。在第二个词完成进入堆栈后,程序似乎崩溃。堆栈实现崩溃时,试图打印堆栈的元素
#include <stdio.h>
#include <stdlib.h>
typedef struct stackElement {
int stringLength;
char *name;
} StackElement;
int Push(StackElement **stack,int *index);
int main()
{
StackElement *stack = NULL;
int index = -1;
Push(&stack,&index);
printf("The index is : %d\n", index);
printf("The top word of the stack is %s\n", stack[index].name);
Push(&stack,&index);
printf("The index is : %d\n", index);//Crashes after this command is executed
printf("The second word of the stack is %s\n", stack[index].name);
system("PAUSE");
return 0;
}
int Push(StackElement **stack,int *index)
{
if (*stack == NULL) {
printf("The stack is empty\n");
*index = *index + 1 ;
*stack = malloc(sizeof(StackElement));
} else {
printf("The stack is not empty\n");
*index = *index + 1 ;
//Adding enough space for one more element in the stack
*stack = realloc(*stack,sizeof(StackElement)*(*index+1));
}
printf("Enter the length of the word you want in the stack\n");
scanf("%d", &(*stack[*index]).stringLength);
(*stack[*index]).name = malloc(sizeof(char)*(*stack[*index]).stringLength);
printf("Enter the word in the stack\n");
scanf("%s", (*stack[*index]).name);
return 0;
}
不是错误来源,但有时候你应该真的释放你的malloc'd空间。也许有人会搜索问题*然后*。附注:这不仅是一个堆栈,与此索引的东西和所有... – deviantfan
我知道,我需要释放占用的空间在某些时候,但我不认为它会导致任何冲突在目前的状态程序。我不明白你对索引的看法,但我会用它作为堆栈的“Top”指标。 – user3385993
对不起,我的编辑,但那些额外的空白行停止你的代码适合框。这对阅读不利。 – SzG