一、malloc函数
malloc函数:
(void *)malloc(int size)
功能:动态分配指定大小的内存空间
输入:指定大小的内存空间(参数大小:字节)
返回类型为:void*,如果分配内存失败,返回的值为NULL(0);
用法:
char *pCh;
pCh = (char *)malloc(1000);
if(pCh = NULL)
{
...内存分配失败的处理代码
}
free函数
void free(void *p)
功能:释放p开头的内存空间(malloc创建的空间大小)
输入:空间的首地址
用法
free(p);
int main()
{
int *p; // 整型指针
p = (int *)malloc(100); // 动态分配100个字节,注意此时的强制转换类型
// 等效于: int array[25] // 数组名array,就是这个数组的首地址
// array[0],array[1]数组使用下标来访问
p[0] = 1;
p[1] = 2;
printf("%d, %d\n", p[0], p[1]);
free(p); // 释放
return 0;
}
二、线性表的链式表示和实现
#include <stdlib.h>
#include <stdio.h>
// 定义一个结构体类型
struct Student{
int num;
char name[10];
struct Student* next; // 指向本结构体的指针
}; // 后面要加分号
int main()
{
struct Student *pStd1, *pStd2; // 定义了 2 个Student结构体的指针
pStd1 = (struct Student*)malloc(sizeof(struct Student)); // 动态分配一个Student结构体
pStd2 = (struct Student*)malloc(sizeof(struct Student));
pStd1->next = pStd2; // 通过next指向pStd2;
pStd1->num = 1;
pStd2->num = 2;
printf("%d\n", pStd1->num);
//printf("%d\n", pStd2->num);
printf("%d\n", pStd1->next->num); // 通过next获取第二个学号
free(pStd1);
//free(pStd2);
free(pStd1->next);
return 0;
}
输出结果为: 1 2