7.23 数据结构day_1
思维导图
知识补充:malloc、free函数的原型
- malloc()函数功能:申请堆区空间
需要包含头文件:#include<stdlib.h>
函数返回值:void * ,使用时,需要强制转换
函数名:malloc
参数:申请空间的字节大小,以字节为单位,可以借助于sizeof()运算符
eg:
单个申请:int *p1 = (int *)malloc(sizeof(int)); // ==>>int *p1 = (int *)malloc(4);
连续申请:int *p2 = (int *)malloc(sizeof(int)*3);
[内存泄漏,申请空间不释放,如何避免:在何时位置释放空间]
- free()函数功能:释放堆区空间
需要包含头文件:#include<stdlib.h>
函数返回值:无 void
函数名:free
参数:要释放的指针(指针存储的堆区空间地址)
eg:
单个释放: free(p1);
连续释放: free(p2);
一、案例
1.案例1 内存空间划分区域解释
#include<stdio.h>
int a;//全局变量 未初始化 静态区 .bss段
int b = 100;//全局变量 已初始化 静态区 .data段
static int c; //全局变量 未初始化 静态区 .bss段
static int d = 200; //全局变量 已初始化 静态区 .data段
const int e = 24; //const修饰的全局变量 静态区 .ro段
char *p = "hello"; // "hello" 在静态区的.ro段。 p是全局变量已初始化 在静态区的.data段
int main(int argc, const char *argv[])
{
int a;//局部变量 栈区
int b = 100;//栈区
static int c; //局部静态变量 未初始化 静态区 .bss段
static int d = 200; //局部静态变量 已初始化 静态区 .data段
const int e = 24; //const修饰的局部变量 栈区
char *p = "hello"; // "hello" 在静态区的.ro段。 p是局部变量 栈区
return 0;
}
2.案例2 在堆区申请空间、释放空间
#include<stdio.h>
#include<stdlib.h> //包含头文件
int main(int argc, const char *argv[])
{
//在堆区申请了4个节点的大小空间,并将地址赋值给p1
int *p1 = (int *)malloc(sizeof(int));
printf("*p1 = %d\n", *p1);
*p1 = 100;
printf("*p1 = %d\n", *p1);
//在堆区连续申请了5个4个字节的大小空间,并将地址赋值给p2,p2访问的是首地址
int *p2 = (int *)malloc(sizeof(int)*5);
for(int i=0; i<5; i++)
{
//printf("%d ", p2[i]);
//printf("%d ", *(p2+i));
//
p2[i] = i+1;
}
for(int i=0; i<5; i++)
{
printf("%d ", p2[i]);
}
printf("\n");
//释放堆区空间
free(p1);
free(p2);
//避免野指针,要给指针置空
p1 = NULL;
p2 = NULL;
return 0;
}
二、作业
1.在堆区申请两个长度为32的空间,实现两个字符串的比较【非函数实现】
1> 定义函数,在对区申请空间
两个申请,主函数需要调用2次
2> 定义函数,实现字符串的输入
void input(char *p)
3> 调用函数实现字符串比较,在主函数中输出大小
int my_strcmp(const char *s1,const char *s2)
4> 定义函数,释放空间
代码如下:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int my_stcmp(char *p1,char *p2);
int main(int argc, const char *argv[])
{
char *p1 = (char *)malloc(sizeof(char)*32);
char *p2 = (char *)malloc(sizeof(char)*32);
printf("input first string:");
gets(p1);
printf("input string:");
gets(p2);
int q=my_stcmp(p1,p2);
printf("%d\n",q);
if(q==0)
{
printf("p1=p2");
}
else if(q>0)
{
printf("p1>p2");
}
else
{
printf("p1<p2");
}
free(p1);
free(p2);
p1 = NULL;
p2 = NULL;
return 0;
}
int my_stcmp(char* p1,char *p2)
{
int i = 0;
while((p1[i]==p2[i])&&(p1[i]!=0&&p2[i]!=0))
{
i++;
}
printf("%c %c\n",p1[i-1],p2[i-1]);
printf("%d\n",i-1);
return p1[i]-p2[i];
}