原代碼主要問題
- 頭文件缺失:
#include <stdio.h>、#include <stdlib.h>。
main 中 S=(struct Stack *)malloc(...) 分配結構體大小錯誤,應分配 sizeof(struct Stack)。
scanf("%c", &e) 讀取字符,但 e 定義为 int,且未處理換行符殘留。
Push(S, &e) 傳遞地址,但函數參數為 char e,類型不匹配。
Pop 返回值邏輯混亂,void 函數不能 return 0。
修正后完整代碼
#include <stdio.h>
#include <stdlib.h>
#define STACK_INIT_SIZE 10
#define STACKINCREMENT 2
typedef struct Stack {
char *base;
char *top;
int stacksize;
} Stack;
Stack* InitStack(Stack *S) {
S->base = (char*)malloc(STACK_INIT_SIZE * sizeof(char));
if (!S->base) { printf("error!"); return NULL; }
S->top = S->base;
S->stacksize = STACK_INIT_SIZE;
return S;
}
Stack* Push(Stack *S, char e) {
if (S->top - S->base == S->stacksize) {
S->base = (char*)realloc(S->base, (S->stacksize + STACKINCREMENT) * sizeof(char));
if (!S->base) { printf("分配空間失敗"); return NULL; }
S->top = S->base + S->stacksize;
S->stacksize += STACKINCREMENT;
}
*(S->top) = e;
S->top++;
return S;
}
void Pop(Stack *S, char *e) {
if (S->top == S->base) { printf("棧為空,無法刪除棧頂元素"); return; }
*e = *(--S->top);
printf("刪除的棧頂元素為:%c\n", *e);
}
int main() {
Stack *S = (Stack*)malloc(sizeof(Stack));
if (!S) { printf("error!"); return 1; }
InitStack(S);
char e, i;
printf("輸入要插入的元素e: ");
scanf(" %c", &e); // 空格跳過換行符
Push(S, e);
Pop(S, &i);
free(S->base);
free(S);
return 0;
}
關鍵修正點
- 結構體定義分離,
main 分配結構體指針而非字符數組。
Push 參數改为值傳遞 char e,Pop 參數改为輸出指針 char *e。
realloc 大小計算修正:(S->stacksize + STACKINCREMENT) * sizeof(char)。
scanf(" %c", ...) 前置空格跳過空白字符。
- 釋放動態內存
free(S->base); free(S);。