在C程序中获得运行时错误

时间:2015-03-01 10:28:42

标签: c pointers stack

很长一段时间后触摸C.我在以下代码中遇到运行时错误。我正在使用的IDE [C-Free]没有显示确切的错误,但它显示了' StackMin.exe'已停止工作。

这里,我使用两个结构,struct stack用于堆栈,struct AdvanedStack用于存储两个堆栈。最后,我想打印AdvancedStack

中的两个堆栈的容量

代码是:

#include<stdio.h>

struct stack {
    int capacity;
    int top;
    int *array;
  };

struct AdvancedStack{

    struct stack* elementStack;
    struct stack* minStack; 

};


struct stack* createStack()
{
    struct stack* myStack= (struct stack*)malloc(sizeof(struct stack));
    myStack->capacity=5;
    myStack->top=-1;
    myStack->array= malloc(myStack->capacity * sizeof(int));

    return myStack;

}

struct AdvancedStack* createAdvancedStack()
{
  struct AdvancedStack *myStack = (struct AdvancedStack*)malloc(sizeof(struct AdvancedStack));
    myStack->elementStack=createStack();
    myStack->minStack=createStack();
}

int main()
{
    struct AdvancedStack* advStack = createAdvancedStack();

   printf("%d",advStack->elementStack->capacity);
    printf("%d",advStack->minStack->capacity);
}

1 个答案:

答案 0 :(得分:3)

您忘记从myStack函数返回createAdvancedStack()

struct AdvancedStack* createAdvancedStack()
{
    struct AdvancedStack *myStack = malloc(sizeof(struct AdvancedStack)); //Don't cast the result of malloc

    myStack->elementStack=createStack();
    myStack->minStack=createStack();

    return myStack; //You forgot this
}

阅读this,了解为什么不应该投射malloc的结果。