很简单,你 malloc 得到的那个地址给了谁,之后就 free 谁
执行了多少次 malloc 就执行多少次 free
*E = (SqStack *)malloc(sizeof(SqStack ));
(*E)->base = (Elemtype *)malloc(MAXSIZE * sizeof(Elemtype ));
// ...
free((*E)->base);
free(*E);
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <stdbool.h>
#define MAXSIZE 20
typedef int Elemtype;
//建立类
typedef struct
{
Elemtype *base; //尾指针
Elemtype *top; //头指针
int StackSize; //剩余空间
}SqStack;
void InitStack(SqStack **E); //初始化创建空栈
void PushStack(SqStack **E, Elemtype N); //进栈
Elemtype PopStack(SqStack *E); //出栈
void DeStack(SqStack **E); //释放内存
bool StackEmpty(SqStack *E); //判断真假
bool StackEmpty(SqStack *E) //判断真假
{
return E->top == E->base;
}
void DeStack(SqStack **E) //释放内存
{
free((*E)->base); free(*E);
/*
while(0 < (*E)->StackSize)
{
(*E)->base++;
(*E)->StackSize--;
free((*E)->top);
(*E)->top = (*E)->base;
}
free(*E);
*/
}
/*void DeStack(SqStack **E) //释放内存
{
Elemtype *temp;
for(int i = 0; i < ((*E)->StackSize); i++)
{
temp = (*E)->base;
(*E)->base++;
free(temp);
}
free(*E);
}*/
Elemtype PopStack(SqStack *E) //出栈
{
E->top--;
E->StackSize++;
return *(E->top);
}
void PushStack(SqStack **E, Elemtype N) //进栈
{
if((*E)->top - (*E)->base >= (*E)->StackSize)
{
(*E)->base = (Elemtype *)realloc((*E)->base, ((*E)->StackSize + MAXSIZE) * sizeof(Elemtype )); //复制前面的base中的数据进入到扩大后的base中
if(!(*E)->base)
{
printf("内存分配失败本程序结束运行\n"); //判断是内存地址是否分配成功
exit(0);
}
(*E)->top = (*E)->base + (*E)->StackSize; //因为以是新的内存空间所有,top中标记的地址也是错误的,所以按照以占用多少空间从新赋予top地址(realloc已经把数据复制过来了)
(*E)->StackSize = (*E)->StackSize + MAXSIZE; //从新赋予记述节点数据
}
*((*E)->top) = N;
(*E)->top++;
(*E)->StackSize--;
}
void InitStack(SqStack **E) //初始化创建空栈
{
*E = (SqStack *)malloc(sizeof(SqStack ));
(*E)->base = (Elemtype *)malloc(MAXSIZE * sizeof(Elemtype )); //向指针类中的base赋予空间
if(!(*E)->base)
{
printf("内存分配失败本程序结束运行\n"); //判断是内存地址是否分配成功
exit(0);
}
(*E)->top = (*E)->base; //把初始地址传给头指针
(*E)->StackSize = MAXSIZE; //初始剩余空间数量
}
int main()
{
SqStack *T, *F;
char litte[32];
Elemtype N = 0;
InitStack(&T);
InitStack(&F);
//把ASCII传给字符串
scanf("%s", litte);
for(int i = 0; litte[i] != 0; i++ )
{
litte[i] = litte[i] - '0';
PushStack(&T,litte[i]);
}
//转十六进制
while(!StackEmpty(T))
{
for(int i = 0; i < 4 && !StackEmpty(T); i++)
{
N += PopStack(T) * pow(2, i); //倒着出栈运算
}
PushStack(&F,N); //在进栈
N = 0;
}
while(F->top != F->base)
{
printf("%x", PopStack(F)); //打印栈中的每一个数据
}
printf("\n");
DeStack(&T);
DeStack(&F);
return 0;
}
|