正确的返回类型是什么?

时间:2019-10-06 10:03:17

标签: c arrays string pointers stack

我的构建失败。我不确定为什么...

  

简介:对于此分配,您必须编写一个c程序,该程序将一个中缀表达式作为输入并显示该输入的后缀表达式。转换为后缀表达式后,程序应从后缀评估表达式并显示结果。

为此,我们必须使用堆栈,而我已经无法构建第一个动态分配的堆栈。

typedef struct stack
{
    int top;
    int capacity;
    int *arr;

} stack;

stack* createStack(int capacity) //create a stack, must allocate a box of memory of pointer to that stack
{
    stack* s = malloc(sizeof(stack)*1);
    s->top = -1; //bc it's a pointer, use an arrow or (*s).top;
    s-> capacity = capacity;   //one's a pointer, one's what's 
          //passed to it
    s-> arr = malloc(sizeof(char)* capacity);
     //defensive coding: checks to see if we found space for the 
                     //array
     if(s->arr == NULL)
     {
        printf("Failed to find space for the array.\n");
        free(s);
        return NULL;
      }
    else
        return s;
}

1 个答案:

答案 0 :(得分:0)

您有整数指针int *arr;,但在代码中分配的内存却较少s-> arr = malloc(sizeof(char)* capacity);

您应该写: s-> arr = malloc(sizeof(int)* capacity);