一、结构体的定义
1.1
struct date
{
char c[20];
double weight;
double length;
int age;
}; //这里的“;”切忌不可省略
#include<stdio.h>
int main()
{
struct date a ={"编程人",98.3,180.3,23};
printf("%s %lf %lf %d\n",a.c,a.weight,a.length,a.age);
return 0;
}
1.2 结构体的嵌套
struct T
{
double weight;
double length;
};
struct S
{
char c;
struct T y;
int a;
double d;
char arr[100];
};
#include<stdio.h>
int main()
{
struct S s = { 'c' ,{55.6,200} , 100 , 3.14 , "编程人" };
printf( "%c %lf %lf %d %lf %s\n", s.c , s.y.weight,s.y.length , s.a , s.d , s.arr );
return 0;
}
二、结构体的对齐规则
struct S1
{
char c1;
char c2;
int a;
};
struct S2
{
char c1;
int a;
char c2;
};
#include<stdio.h>
int main()
{
struct S1 s1 = {0};
printf("%d\n",sizeof(s1));
struct S2 s2 = {0};
printf("%d\n",sizeof(s2));
}
这个是我关于上面一些代码的讲解(讲的不是很好):https://share.weiyun.com/qLSChsM8
三、求结构体各个变量的偏移量
利用offsetof函数求,头文件是stddef.h,最好还是能看一下上面的视频~~
#include<stddef.h>
#include<stdio.h>
struct s2
{
char c;
int i;
double d;
};
#include<stdio.h>
int main()
{
printf("%d\n",offsetof(struct s2,i)); //0
printf("%d\n",offsetof(struct s2,c)); //4
printf("%d\n",offsetof(struct s2,d)); //8
printf("%d\n",sizeof(s2));
return 0;
}
*/
|