C语⾔学习笔记——组合数据类型⽬录
⼀、结构体
例1:
结构体变量的⼏种赋值⽅式:测试代码如下:
char name[20];
char sex;
int age;
};
void main(int argc, char const *argv[])
{
//定义并且依次赋值
struct student a={"xiaoming",'m',18};
//定义并且不按顺序赋值
struct student b={.age = 20,.name = "xiaobai",.sex = 'f'};
//对结构体成员⾥⾯每⼀个成员赋值
struct student c = {0};//定义⼀个结构体变量,并且清空
strcpy(c.name,"xiaohua");
c.sex = 'm';
c.age = 18;
//打印查看结果
printf("a.name = %s , a.sex = %c ,a.age = %d\n",a.name,a.sex,a.age);
printf("b.name = %s , b.sex = %c ,b.age = %d\n",b.name,b.sex,b.age);
printf("c.name = %s , c.sex = %c ,c.age = %d\n",c.name,c.sex,c.age);
return ;
}
输出结果,如图所⽰:
例2:
通过结构体指针赋值:
为⼀个结构体指针分配⼀块堆空间再利⽤该指针往堆空间中进⾏赋值测试代码如下:
为⼀个结构体指针分配⼀块堆空间
再利⽤该指针往堆空间中进⾏赋值
*/
struct student
{
char name[20];
char sex;
int age;
};
c++string类型void main(int argc, char const *argv[])
{
//定义⼀个结构体指针
struct student *p = NULL;
//将结构体指针指向堆空间
p = (struct student *)malloc(2*sizeof(struct student));
//⽤指针往堆空间中进⾏赋值
strcpy(p->name,"xiaobai");
p->sex = 'm';
p->age = 21;
strcpy((p+1)->name,"zhanghua");
(p+1)->sex = 'f';
(p+1)->age = 20;
//打印
printf("p.name = %s , p.sex = %c , p.age = %d\n",p->name,p->sex,p->age);
printf("(p+1).name = %s , (p+1).sex = %c , (p+1).age = %d\n",(p+1)->name,(p+1)->sex,(p+1)->age);
return ;
}
输出结果,如图所⽰:
例3:
结构体的空间分配:
与类型的摆放顺序有关
与结构体中需要空间最⼤的基本类型有关
测试代码如下:
//按占⽤空间最⼤的基本类型来分
struct test
{
char a;
};
struct test1
{
char a;
short b;
};
struct test2
{
char a;
int b;
};
//结构体所⽤空间与,类型顺序有关
struct test3
{
char a;
int b;
short c;
};
struct test4
{
char a;
short c;
int b;
};
struct test5
{
char a;
short b;
};
struct test6
{
short b;
char a;
};
void main(int argc, char const *argv[])
{
printf("按占⽤空间最⼤的基本类型来分:\n");
printf("struct test ={char a} ----> = %d\n",sizeof(struct test));
printf("struct test1 ={char a;short b;} ----> = %d\n",sizeof(struct test1));
printf("struct test2 ={char a;int b} ----> = %d\n",sizeof(struct test2));
printf("====================================================\n"); printf("结构体所⽤空间,与类型的顺序有关:\n");
printf("4字节对齐:\n");
printf("struct test3 ={char a;int b;short c;} ----> = %d\n",sizeof(struct test3)); printf("struct test4 ={char a;short c;int b;} ----> = %d\n",sizeof(struct test4)); printf("2字节对齐:\n");
printf("struct test5 ={char a;short b;} ----> %d\n",sizeof(struct test5));
printf("struct test6 ={short b;char a;} ----> %d\n",sizeof(struct test6));
return;
}
输出结果,如图所⽰:
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论