编写一个C程序来显示结构成员的大小和偏移量
问题
编写一个C程序来定义结构并显示成员变量的大小和偏移量
结构-它是不同数据类型变量的集合,在一个名称下组合在一起。
结构声明的一般形式
datatype member1; struct tagname{ datatype member2; datatype member n; };
在这里,struct-关键字
标记名-指定结构名称
member1,member2-指定构成结构的数据项。
例子
struct book{ int pages; char author [30]; float price; };
结构变量
有三种声明结构变量的方法-
方法一
struct book{ int pages; char author[30]; float price; }b;
方法二
struct{ int pages; char author[30]; float price; }b;
方法三
struct book{ int pages; char author[30]; float price; }; struct book b;
结构的初始化和访问
成员和结构变量之间的链接是使用成员运算符(或)点运算符建立的。
初始化可以通过以下方式完成-
方法一
struct book{ int pages; char author[30]; float price; } b = {100, "balu", 325.75};
方法二
struct book{ int pages; char author[30]; float price; }; struct book b = {100, "balu", 325.75};
方法三(使用成员运算符)
struct book{ int pages; char author[30]; float price; } ; struct book b; b. pages = 100; strcpy (b.author, "balu"); b.price = 325.75;
方法四(使用scanf函数)
struct book{ int pages; char author[30]; float price; } ; struct book b; scanf ("%d", &b.pages); scanf ("%s", b.author); scanf ("%f", &b. price);
使用数据成员声明结构并尝试打印它们的偏移值以及结构的大小。
程序
#include输出结果#include struct tutorial{ int a; int b; char c[4]; float d; double e; }; int main(){ struct tutorial t1; printf("the size 'a' is :%d\n",sizeof(t1.a)); printf("the size 'b' is :%d\n",sizeof(t1.b)); printf("the size 'c' is :%d\n",sizeof(t1.c)); printf("the size 'd' is :%d\n",sizeof(t1.d)); printf("the size 'e' is :%d\n",sizeof(t1.e)); printf("the offset 'a' is :%d\n",offsetof(struct tutorial,a)); printf("the offset 'b' is :%d\n",offsetof(struct tutorial,b)); printf("the offset 'c' is :%d\n",offsetof(struct tutorial,c)); printf("the offset 'd' is :%d\n",offsetof(struct tutorial,d)); printf("the offset 'e' is :%d\n\n",offsetof(struct tutorial,e)); printf("size of the structure tutorial is :%d",sizeof(t1)); return 0; }
the size 'a' is :4 the size 'b' is :4 the size 'c' is :4 the size 'd' is :4 the size 'e' is :8 the offset 'a' is :0 the offset 'b' is :4 the offset 'c' is :8 the offset 'd' is :12 the offset 'e' is :16 size of the structure tutorial is :24