300字范文,内容丰富有趣,生活中的好帮手!
300字范文 > 结构体的使用和动态内存的分配及释放

结构体的使用和动态内存的分配及释放

时间:2018-10-13 12:02:17

相关推荐

结构体的使用和动态内存的分配及释放

结构体

什么是结构体?结构体是用户根据实际需要自己定义的复合数据类型。结构体的出现是为了表示一些复杂的数据,而普通的数据类型无法满足要求。

结构体的定义:

struct Student //struct Student为一个复合数据类型,结构体名字为Student,含有三个成员sno,name,age{ int sno;char name[20];int age;};//分号不能省

实例说明1:

#include<stdio.h>#include<string.h>struct Student{int sno;char name[20];int age;};//分号不能省int main(){struct Student st,*pst;pst=&st;/*第一种方式:结构体变量.成员*/st.sno=99;strcpy(st.name,"李四");//这里的strcpy(st.name,"李四")是string类型的赋值st.age=21;printf("%d,%s,%d\n",st.sno,st.name,st.age);/*第二种方式:pst指向结构体变量中的sno成员,推荐使用*/pst->sno=100;//pst->sno等价于(*pst).snostrcpy(pst->name,"王五");pst->age=30;printf("%d,%s,%d\n",pst->sno,pst->name,pst->age); return 0;}

实例说明2(通过指针传参(在普通变量的数据类型大于4个字节时)可以节省内存和时间,还可以修改成员变量的值):

#include<stdio.h>#include<string.h>struct Student{int sno;char name[20];int age;};void input(struct Student *pst);//前置声明void output(struct Student *pst);int main(){struct Student st;//定义结构体变量st,同时为st分配内存(此时st占28个字节)input(&st);output(&st);return 0;}void output(struct Student *pst)//完成输出{printf("%d %s %d\n",pst->sno,pst->name,pst->age);}void input(struct Student *pst)//完成输入{(*pst).sno=100;strcpy(pst->name,"张三");pst->age=21;}

注意:

1.结构体在定义时并没有分配内存(它只是一个模型),而是在定义结构体变量时分配内存。

2.结构体变量(如上面的st)不能进行四则运算,但可以相互赋值。

动态内存的分配和释放

使用了malloc()函数的都可以称为动态分配内存。malloc()带一个整型参数

如:int *pArr=(int *)malloc(sizeof(int)*5);

说明:其中的malloc函数只能返回第一个字节的地址(无实际意义),所以要就行强制类型转换,这里加(int *);

动态内存的释放:free(pArr);

说明:把pArr所代表的动态分配的20个字节的内存释放(局部变量在函数内执行完就释放了),跨函数使用内存只能通过动态分配内存来实现。

实例说明(跨函数使用内存):

#include<stdio.h>#include<malloc.h>struct Student{int sno;int age;};struct Student* CreateStudent(void);//void表示该方法不加形参,可不写void ShowStudent(struct Student *);int main(){struct Student *ps; ps=CreateStudent();ShowStudent(ps);//将ps赋给pstfree(ps);return 0;}struct Student* CreateStudent(void){struct Student *p=(struct Student*)malloc(sizeof(struct Student));//为结构体指针变量p动态分配内存p->sno=1001;p->age=22;return p;//把p赋给ps,此时ps指向p所指内存地址}void ShowStudent(struct Student *pst){printf("%d %d\n",pst->sno,pst->age);//通过pst指向结构体变量ps的成员sno、age进行输出成员值}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。