-2
以下是一個程序我用C使用數組和指針由執行堆棧的:ERROR使用malloc()和sizeof()函數時
#include<stdio.h>
#include<stdlib.h>
struct ArrayStack {
int top;
int capacity;
int *array;
};
struct ArrayStack *createStack(int cap) {
struct ArrayStack *stack;
stack = malloc(sizeof(struct Arraystack));
stack->capacity = cap;
stack->top = -1;
stack->array(malloc(sizeof(int) * stack->capacity));
return stack;
}
int isFull(struct ArrayStack *stack) {
if(stack->top == stack->capacity-1)
return 1;
else
return 0;
}
int isEmpty(struct ArrayStack *stack) {
if(stack->top == -1)
return 1;
else
return 0;
}
void push(struct ArrayStack *stack, int item) {
if(!isFull(stack)) {
stack->top++;
stack->array[stack->top] = item;
} else {
printf("No more memory available!");
}
}
void pop(struct ArrayStack *stack) {
int item;
if(!isEmpty(stack)) {
item = stack->array[stack->top];
stack->top--;
} else {
printf("Memory is already empty!");
}
}
int main() {
struct ArrayStack *stack;
stack = createStack(10);
int choise;
int item;
while(1) {
system("clear");
printf("\n1. Push");
printf("\n2. Pop");
printf("\n3. Exit");
printf("\n\n\n\t\tPlease choose your option!");
scanf("%d",&choise);
switch(choise) {
case 1:
printf("\nEnter a number");
scanf("%d",&item);
push(stack,item);
break;
case 2:
pop(stack);
break;
case 3:
exit(0);
break;
default :
printf("\nPlease enter a valid choise!");
break;
}
}
}
以下錯誤快到每當我試圖編譯該代碼使用gcc編譯器:
prog.c:10:25: error: invalid application of 'sizeof' to incomplete type 'struct Arraystack'
stack = malloc(sizeof(struct Arraystack));
^
prog.c:13:3: error: called object is not a function or function pointer
stack->array(malloc(sizeof(int) * stack->capacity));
^
我已經使用在線IDE如ideone和codechef的ide,但同樣的錯誤再次出現。我完全被打擊了,這真的很煩人!
'sizeof(struct ArrayStack)'大寫'S'投票結束爲錯字 – Danh