我想創建一個堆棧,我可以將整數推入它。到目前爲止,我有這樣的:如何創建一個空棧?
#include <stdio.h>
#define N 20
typedef struct {
int data[N]; // array of at most size N
// N should be a constant declared globally
int top;
} stack_t;
void push(stack_t *stack, int element);
int main(){
void push(stack_t *stack, int n) {
if (stack->top == N - 1) {
printf("Warning: Stack is full, You can't add'\n");
return;
} else {
stack->data[++stack->top] = n;
}
}
stack_t * e_stack; // Empty stack created
push(e_stack, 2);
}
但是,這段代碼給出了一個運行時錯誤。我認爲這是因爲這部分是錯誤的: stack_t * e_stack;創建//空棧
(這可能沒有創建一個空棧)
但我知道它是如何錯誤
什麼是嵌套函數thingy?你應該在'main()'之外定義'push()'函數。只有在flaccid模式下的GCC允許嵌套函數 - 它們不可移植且通常是邪惡的,如果您正在學習C,則不應該使用它們(並且即使在您學習C之後也可能不會使用它們)。 –