【问题标题】:ERROR when using malloc() and sizeof() function使用 malloc() 和 sizeof() 函数时出错
【发布时间】:2017-04-03 20:56:17
【问题描述】:

以下是我用 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,但同样的错误再次出现。我完全被震惊了,这真的很烦人!

【问题讨论】:

  • sizeof(struct ArrayStack) 大写字母S 因打字错误投票结束

标签: c arrays pointers gcc stack


【解决方案1】:

首先你的错误:

stack = malloc(sizeof(struct ArrayStack));

您输入了Arraystack(小写s)。

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

您输入了 stack-&gt;array(malloc(sizeof(int) * stack-&gt;capacity));,这在语法上是一个函数调用,这就是编译器抱怨 array 不是函数指针的原因。

另外:

  1. createStack() 中的malloc()ed 空间中将函数void destroyStack(ArrayStack* stack) 引入free()。完成堆栈后,在 main() 末尾调用它。

始终向free() 呈现malloc() 向你呈现的内容。

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

【讨论】:

    猜你喜欢
    • 2014-05-21
    • 2015-11-22
    • 2013-02-19
    • 2017-12-01
    • 2014-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多