1.动态申请内存块,原型:
void * malloc(int x);
功能:申请大小为x的内存块,返回所分配内存起始地址或空指针.该空间是在堆中分配的.
释放内存:
void free(void *p);
p所指的内存区域一定是由函数malloc分配的.
2.定义新类型名:
typedef 复合说明项
其好处在于:能为c语言中没有名字的数据类型定义一个名字.
例如:
typedef int T; T a, b[10];
typedef int *IP; IP p, *q, r[10]; <==> int *p, **q, *r[10];
typedef int A[10]; A x, y[5], *p; <==> int x[10], y[5][10], (*p)[10];
typedef int F(int); F *f; <==> int (*f)(int);
c语言中唯一的一个先使用后定义的情况:
typedef struct node NODE;
struct node {
int info;
NODE *next;
};
3.链表插入(按值从小到大排列)
示例程序代码如下:
#include "stdio.h"
#include "malloc.h"
typedef struct node NODE;
struct node {
int info;
NODE *next;
};
//链表插入,不正确.
void insert(NODE *h, int x){
NODE *p = h, *q, *r;
while(p != NULL && p->info < x){
q = p;
p = p->next;
}
//生成一个新节点
r = (NODE *)malloc(sizeof(NODE));
r->info = x;
if(h != p){
q->next = r;
r->next = p;
}else{
r->next = h;
h = r;
}
}
//链表插入,法一.
void insert1(NODE **h, int x){
NODE *p = *h, *q, *r;
while(p != NULL && p->info < x){
q = p;
p = p->next;
}
//生成一个新节点
r = (NODE *)malloc(sizeof(NODE));
r->info = x;
if(*h != p){
q->next = r;
r->next = p;
}else{
r->next = *h;
*h = r;
}
}
//链表插入,法二.
NODE * insert2(NODE *h, int x){
NODE *p = h, *q, *r;
while(p != NULL && p->info < x){
q = p;
p = p->next;
}
//生成一个新节点
r = (NODE *)malloc(sizeof(NODE));
r->info = x;
if(h != p){
q->next = r;
r->next = p;
}else{
r->next = h;
h = r;
}
return h;
}
//打印链表
void print(NODE *h){
while(h){
printf("%d/t", h->info);
h = h->next;
}
}
void main()
{
NODE *head = NULL;
//insert(head, 10);
//insert(head, 20);
//insert(head, 15);
//什么也没打印,具体分析略,应如何改?
//print(head);
//法一,传指针,改变head值
//insert1(&head, 10);
//insert1(&head, 20);
//insert1(&head, 15);
//print(head);
//法二,返回头节点
head = insert2(head, 10);
head = insert2(head, 20);
head = insert2(head, 15);
print(head);
}