很长一段时间后触摸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);
}
答案 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
的结果。