您的位置:首页 > 编程语言 > C语言/C++

【c语言】用malloc函数给结构体赋值的使用方法,free清空

2015-05-24 14:53 183 查看
我们知道,结构体使用之前必须的赋初值,例如:

struct A

{

char *na;

}*p;

对这个结构体而言,如不对char *na和*p赋初值 ,这个程序就通不过,*p是一个结构体指针,所以我们要找到它要指的地方就必须知道*na的地址,于是仅有na有初值才知道*p的指向,即他保存的地址。同理要找到p在哪里,就得对p赋初值。

下面我们用malloc函数动态分配空间给结构体对象。并使用free函数清空。

代码如下:
#include <stdio.h>
#include <string.h>
#include <malloc.h>

struct student
{
char *name;
int score;
}*pstu;

int main()
{
pstu = (struct student *)malloc(sizeof(struct student));//给pstu赋初值,找到指针所在位置
pstu->name = (char *)malloc(10*sizeof(char));//对name赋初值,让pstu能找到它
strcpy(pstu->name,"bit-tech");//用strcpy函数给name赋值
printf("%s",pstu->name);
free(pstu->name);//清空的先后顺序也很重要,若先清空pstu,那么name的位置则无法确定,就无法清空。
free(pstu);
return 0;
}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: