本人初学数据结构,遇见free()函数问题,求解惑
1、头文件:/* Project_3_1.h */
/* 用链表结构和堆栈实现二进制转换 */
#include<stdio.h>
#include<stdlib.h>
/* 声明链表结构 */
typedef struct stack *stackPointer;
typedef struct stack {
int num;
stackPointer link;
};
/* 建立一个空链表 */
void Create(stackPointer *top){
*top = NULL;
}
/* 判断是否为满 */
int IsFull();
/* 入栈 */
void Push(stackPointer *top, int x){
stackPointer temp = (stackPointer)malloc(sizeof(stackPointer*));
temp->num = x;
temp->link = *top;
*top = temp;
}
/* 判断是否为空 */
int IsEmpty(){
fprintf(stderr, "\n");
exit(EXIT_FAILURE);
}
/* 出栈 */
int Pop(stackPointer *top){
stackPointer temp;
if((*top)){
int x = (*top)->num;
temp = *top;
*top = (*top)->link;
free(temp); /* 调试后卡住的断点 */
return x;
}
else
return IsEmpty();
}
/* 二进制转换函数 */
void Conversion(stackPointer *top, int *n){
printf("Please input the decimal number: ");
scanf("%d", n);
Create(top);
while(*n){
int x = (*n) % 2;
Push(top, x);
(*n) /= 2;
}
printf("The corresponding binary version is: ");
while(*top){
int x = Pop(top);
printf("%d", x);
}
}
2、main函数:
/* Project_3_1 main */
#include"Project_3_1.h"
int main(void){
stackPointer top;
int n;
Conversion(&top, &n);
printf("\n");
return 0;
}
:dizzy:求大神解惑 free()释放的是指针指向的内存! 小甲鱼的二师兄 发表于 2014-11-8 14:35
free()释放的是指针指向的内存!
嗯嗯,那该怎么改,我改了很多次,就是不知道temp应该赋值什么,指针这块有点乱:cry 已解决~
最终的代码改成这样了:
/* Project_3_1.c */
/* 用链表结构和堆栈实现二进制转换 */
#include<stdio.h>
#include<stdlib.h>
#define MALLOC(p, s) (p) = malloc(s)
/* 声明链表结构 */
typedef struct stack *stackPointer;
typedef struct stack {
int num;
stackPointer link;
};
void Create(stackPointer *top);
void Push(stackPointer *top, int x);
int Pop(stackPointer *top);
void Conversion(stackPointer *top, int *n);
int IsEmpty();
int IsFull();
int main(void){
stackPointer top;
int n;
int t = 0;
while (++t)
Conversion(&top, &n);
printf("\n");
return 0;
}
/* 建立一个空链表 */
void Create(stackPointer *top){
*top = NULL;
}
/* 判断是否为满 */
int IsFull();
/* 入栈 */
void Push(stackPointer *top, int x){
stackPointer temp;
MALLOC(temp, sizeof(*temp));
temp->num = x;
temp->link = *top;
*top = temp;
}
/* 判断是否为空 */
int IsEmpty(){
fprintf(stderr, "\n");
exit(EXIT_FAILURE);
}
/* 出栈 */
int Pop(stackPointer *top){
stackPointer temp = *top;
if ((*top)){
int x = (*top)->num;
(*top) = (*top)->link;
free(temp); /* 调试后卡住的断点 */
return x;
}
else
return IsEmpty();
}
/* 二进制转换函数 */
void Conversion(stackPointer *top, int *n){
printf("Please input the decimal number: ");
scanf("%d", n);
Create(top);
while (*n){
int x = (*n) % 2;
Push(top, x);
(*n) /= 2;
}
printf("The corresponding binary version is: ");
while (*top){
int x = Pop(top);
printf("%d", x);
}
printf("\n\n");
}
thanks!
页:
[1]