关于返回临时对象的问题
写了一个stack实现
typedef int ElemType;
const INIT_SIZE = 10;
typedef struct Stack
{
ElemType* top, *base;
int SIZE;
}stack;
stack initStack()
{
stack s;
s.SIZE = INIT_SIZE;
ElemType block[s.SIZE];
s.base = block;
s.top = s.base;
return s;
}
void push(stack* s, ElemType e)
{
if(s-> top - s-> base == s-> SIZE)
return;
*(s-> top++) = e;
}
ElemType topof(stack* s)
{
if(s-> top == s-> base)
return 0;
return *(s-> top-1);
}
void pop(stack* s, ElemType e)
{
if(s-> top == s-> base)
e = 0;
e = *(--s-> top);
}
int isEmpty(stack* s)
{
return s-> top == s-> base;
}
void print(stack* s)
{
if(isEmpty(s))
{
printf( "the stack is Empty!\n ");
return;
}
ElemType* ptr =&(*(s-> base));
while(s-> base != ptr)
printf( "%d\t ",*ptr);
printf( "\n ");
}
int main()
{
stack st = initStack();----问题出在这里,
printf( "%d\t%d\n ", st.top,st.base);
int i;
for(i = 1; i < 6; ++i)
push(&st,i);
print(&st); //打印时除了base指向的元素,其余元素均和不正常。
printf( "%d\t%d\n ", st.base, st.top);
ElemType e;
while(!isEmpty(&st))
pop(&st,e);
print(&st);
return 0;
}
不知道怎么回事,哪位给解释一下。
[解决办法]
initStack中,
ElemType block[s.SIZE];
block是临时的,函数执行完后地址就无意义了!
-> >
ElemType* block = new ElemType[s.SIZE];
[解决办法]
stack initStack()
{
stack s;
s.SIZE = INIT_SIZE;
ElemType block[s.SIZE];
s.base = block;
s.top = s.base;
return s;
}
....
stack st = initStack();
---------------------------
s是局部变量,函数执行完,s就释放了。
你赋值给了st,默认的位拷贝,st内的指针指向的内存已经被释放了,不可用。
修改initStack函数的参数为initStack(stack& s)