首先我们来看一道题:
#include #include #include struct student { char *name; //改 char name [ ]; int score; }*pstu; int main()
{ pstu=(struct student*)malloc(sizeof(struct student)); ///将地址转成struct student* 型 改:char *p=NULL; strcpy(pstu->name,“tom”); pstu->score=99; 改:char *p=NULL; printf(“name =%s,score =%d\n”,pstu->name,pstu->score); free§; return 0; }
原式是一个野指针问题,为了避免出现野指针,通常我们需要将指针初始化为NULL,用完后也为其赋值为NULL。 结构体成员指针往往会被我们忽视,所以说注意它也需要初始化,且需要为结构体指针分配足够的内存!那么就用到了malloc这个宏,使用方法如下:
给指针变量赋初值:
方法一:char * p = (char * )malloc(sizeof(char));
方法二:char * p = NULL;
给数组赋初值:
方法一: int a[10] = {0};
方法二: memset(a, 0, sizeof(a));
memset函数有3个参数:第一个是要被设置的内存起始地址;第二个是要被设置的值;第三个是要被设置的内存大小,单位为字节;注意不要混淆:
给结构体指针赋初值:
方法一: pstu = (struct student *)malloc(sizeof(struct student));
常见错误: pstu = (struct student *)malloc(sizeof(struct student *));
使用完指针后务必记得释放指针所指向的内存,否则不知道什么时候我们又改变了指针的值,使其变成了野指针!
这里就需要free§这个函数的帮忙了,它可以切断指针与指向内存的联系。但是需要注意的是free对于同一指针变量只能使用一次。不然会导致出错或者内存泄漏。
释放完内存后另指针的值变为NULL!
如下:
free§; p = NULL;
另外补充一下动态内存分配的有关函数 开辟动态存储区 #include
malloc voidmalloc(unsigned int size); 在内存的动态存储区分配一个长度为size的连续空间 malloc(100) a=(int )malloc(nsizeof(int)) 将nsizeof(int)个内存给a
calloc void*calloc(unsigned n,unsigned size); 在内存的动态存储区分配n个长度为size的连续空间 p=calloc(50,4) 50x4个字节的临时分配域;
relloc voidrelloc(voidp,unsigned int size); 重新分配动态存储区; relloc(p,50) 将p所指向的已分配的动态空间改为50字节;
free void free(void*p); 释放动态存储区 free(p)释放指针p所指向的已分配的动态空间;