使用malloc()和sizeof()函数时出错

时间:2016-11-20 11:46:21

标签: c arrays pointers gcc stack

以下是我在C中用于使用数组和指针实现堆栈的程序:

#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));
   ^

我使用了像ideone和codechef的ide在线IDE,但同样的错误又来了。我很震惊,这真烦人!

1 个答案:

答案 0 :(得分: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()结束时调用它。
  2. 始终向malloc()呈现pop()向你呈现的内容。

    1. 您的push()未返回弹出值。
    2. pop()public void extendsExample(){ Set<? extends List<? extends String>> setOfList = new HashSet<>(); Set<ArrayList<String>> setOfArrayList = new HashSet<>(); // now setOfList var refers to a set // which contains a arraylist of String setOfList = setOfArrayList; // compilation fails setOfList.add(new LinkedList<String>()); } 失败时,您应该返回指示失败的值。