我想實現一個使用數組的動態堆棧。用戶輸入他想要放入堆棧的單詞的字母數。如果堆棧爲空,則會創建一個塊來保存用戶傳遞到堆棧的信息。如果沒有,那麼堆棧被重新分配,以便它可以保存更多的信息塊(單詞)。然後用戶輸入他想要放入堆棧的單詞(在打印堆棧索引的那一部分)。在第二個詞完成進入堆棧後,程序似乎崩潰。堆棧實現崩潰時,試圖打印堆棧的元素
#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