结构体的使⽤和动态内存的分配及释放
结构体
什么是结构体?结构体是⽤户根据实际需要⾃⼰定义的复合数据类型。结构体的出现是为了表⽰⼀些复杂的数据,⽽普通的数据类型⽆法满⾜要求。
结构体的定义:
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).sno
strcpy(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赋给pst
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进⾏输出成员值
}
>sizeof结构体大小