c语言的动态内存管理函数实现动态内存管理;
1、malloc() 函数
void *malloc(unsigned int size);
分配一块长度为size字节的连续空间,并将该空间的首地址作为函数的返回值。
2、calloc()函数
void *calloc(unsigned int n, unsigned int size);
分配一块长度为n*size字节的连续空间,并将该空间的首地址作为函数的返回值。
3、free()函数
void free(void *block);
释放分配给指针变量block的动态空间。
代码:
#include <stdio.h>
#include <stdlib.h>
#define N 4
struct node{
int data;
struct node *next;
};
int main(int argc, char *argv[]) {
struct node *create_node(void);
struct node *create_list(int);
void out_list(struct node *);
struct node *head=NULL;
head=create_list(N);
out_list(head);
return 0;
}
//创建节点
struct node *create_node(void){
struct node *p;
p=(struct node *)calloc(1,sizeof(struct node));
scanf("%d",&(p->data));
p->next=NULL;
return p;
}
//创建链表
struct node *create_list(int n){
struct node *new,*head,*p;
int i;
if(n>=1){
new=create_node();
head=new;
p=new; /*p指向链表最后一个节点*/
}
for(i=2;i<=n;i++){
new=create_node();
p->next=new;
p=new;
}
if(n>=1){
return head;
}
else{
return NULL;
}
}
//输出链表
void out_list(struct node *head){
struct node *p;
if(head!=NULL){
p=head;
while(p!=NULL){
printf("%d",p->data);
p=p->next;
}
}
}
//删除节点p
struct node *delete(struct node *head,struct node *P){
struct node *q;
if(p==NULL){
return head;
}
if(p==head){
head=head->next;
}
else{
q=head;
while(q->next!=p){
q=q->next;
}
q->next=p->next;
}
free(p);
return head;
}
//查找data=x的节点
struct node *find(struct node *head,int x){
struct node *q;
q=head;
while(p!=NULL&&p->data!=x){
p=p->next;
}
if(p==NULL){
return NULL;
}
else{
return p;
}
}
注意:C语言中,%c前面的空格就是用来屏蔽空白符(空格、换行符、制表符的。对于scanf()而言,%c是个较为特殊的说明符。 %c前没空格,scanf()将读取标准输入流中的第一个字符,%c前有空格,scanf()则读取标准输入流中第一个非空白字符。