一、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);
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;
pStd1 = (struct Student*)malloc(sizeof(struct Student));
pStd2 = (struct Student*)malloc(sizeof(struct Student));
pStd1->next = pStd2;
pStd1->num = 1;
pStd2->num = 2;
printf("%d\n", pStd1->num);
printf("%d\n", pStd1->next->num);
free(pStd1);
free(pStd1->next);
return 0;
}
输出结果为: 1 2
|