这个输出怪异现象是什么道理
下面是一个程序,建立一个6大小的栈,然后往栈内压入6个数,然后输出后三个数。我在main里面最开始加了
printf("123\n");这是为了证明我的编译器可以运行。为什么我加了这一句得到想要的结果
123
6 5 4
Press any key to continue
而没有这一句(把printf("123\n")注释掉)反而什么输出也没有
Press any key to continue
这是什么原因?
#include "stdafx.h"
#include "stdio.h"
#include "stdlib.h"
typedef int Item;
typedef struct stack
{
Item *top;
Item *save;
void CreateStac
}Stack;k(Stack *p, int size);
void PushStack(Item item, Stack *p);
void ReverseShowStack(Stack *p, int size);
int main(void)
{
printf("123\n");
Stack A;
CreateStack(&A, 6);
PushStack(1, &A);
PushStack(2, &A);
PushStack(3, &A);
PushStack(4, &A);
PushStack(5, &A);
PushStack(6, &A);
ReverseShowStack(&A,3);
printf("\n");
return 0;
}
void CreateStack(Stack *p, int size)
{
p->save = (Item *)malloc(sizeof(Item));
p->top = p->save+size;
}
void PushStack(Item item, Stack *p)
{
*(p->top) = item;
p->top--;
}
void ReverseShowStack(Stack *p, int size)
{
Item *copy;
copy = p->top+1;
while(copy != p->top+1+size)
{
printf("%d ", *(copy));
copy++;
}
}
{
p->save = (Item *)malloc(sizeof(Item));
p->top = p->save+size;//p->top已经越界了吧
}
void PushStack(Item item, Stack *p)
{
*(p->top) = item;//第一次push就使用了这个越界的p->top
p->top--;
}
[解决办法]
void CreateStack(Stack *p, int size)
{
p->save = (Item *)malloc(sizeof(Item)*size);//貌似还少个size
p->top = p->save+size;
}
[解决办法]
p->save = (Item *)malloc(sizeof(Item));
-------------------------
内存申请少了,p->save = (Item *)malloc(sizeof(Item)*size);
[解决办法]