2016-11-20 84 views
-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,但同样的错误再次出现。我完全被打击了,这真的很烦人!

+2

'sizeof(struct ArrayStack)'大写'S'投票结束为错字 – Danh

回答

1

首先你的错误:

stack = malloc(sizeof(struct ArrayStack)); 

您键入Arraystack(小写s)。

stack->array=malloc(sizeof(int) * stack->capacity); 

您输入stack->array(malloc(sizeof(int) * stack->capacity));这在语法上是一个函数调用这就是为什么编译器抱怨array不是一个函数指针。

此外:

  1. 介绍的功能void destroyStack(ArrayStack* stack)free()malloc()编空间createStack()。当你完成堆栈时,将它称为main()

总是渲染到free()什么malloc()呈现给你。

  1. 您的pop()不会返回弹出的值。
  2. push()pop()失败时,您应该返回指示失败的值。