【发布时间】:2014-03-13 15:45:01
【问题描述】:
我正在尝试使用数组实现动态堆栈。用户输入他想要放入堆栈的单词的字母数。如果堆栈为空,则创建一个块来保存用户传递给堆栈的信息。如果不是,则重新分配堆栈,以便它可以再容纳一个信息块(字)。然后用户输入他想要放入堆栈的单词(在堆栈索引打印的部分)。第二个词入栈后,程序似乎崩溃了。
#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 空间。也许有人会搜索问题然后。旁注:这不仅仅是一个堆栈,还有这个索引的东西和所有......
-
我知道我需要在某个时候释放占用的空间,但我认为它不会在程序的当前状态下导致任何冲突。我不明白您对索引的看法,但我会将其用作堆栈具有的“顶部”指标。
-
抱歉我的编辑,但那些额外的空白行阻止了您的代码适合该框。这不利于阅读。
-
没关系。谢谢朋友的指正。
标签: c pointers data-structures stack