问题
结构体 – 它是一个不同数据类型变量的集合,组合在一个名称下。
结构声明的一般形式
datatype member1;struct tagname{ datatype member2; datatype member n;};
登录后复制
在这里,struct – 关键字
tagname – 指定结构的名称
member1, member2 – 指定构成结构的数据项。
示例
struct book{ int pages; char author [30]; float price;};
登录后复制
结构体变量
声明结构体变量有三种方式 –
方法一
struct book{ int pages; char author[30]; float price;}b;
登录后复制
方法2
struct{ int pages; char author[30]; float price;}b;
登录后复制
方法三
struct book{ int pages; char author[30]; float price;};struct book b;
登录后复制
初始化和访问结构
成员与结构变量之间的链接是通过成员运算符(或者点运算符)建立的。
可以通过以下方式进行初始化:
方法1
struct book{ int pages; char author[30]; float price;} b = {100, "balu", 325.75};
登录后复制
方法2
struct book{ int pages; char author[30]; float price;};struct book b = {100, "balu", 325.75};
登录后复制
方法3(使用成员运算符)
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#includestruct tutorial{ int a; int b; char c[4]; float d; double e;};int main(){ struct tutorial t1; printf("the size 'a' is :%d",sizeof(t1.a)); printf("the size 'b' is :%d
",sizeof(t1.b)); printf("the size 'c' is :%d
",sizeof(t1.c)); printf("the size 'd' is :%d
",sizeof(t1.d)); printf("the size 'e' is :%d
",sizeof(t1.e)); printf("the offset 'a' is :%d
",offsetof(struct tutorial,a)); printf("the offset 'b' is :%d
",offsetof(struct tutorial,b)); printf("the offset 'c' is :%d
",offsetof(struct tutorial,c)); printf("the offset 'd' is :%d
",offsetof(struct tutorial,d)); printf("the offset 'e' is :%d
",offsetof(struct tutorial,e)); printf("size of the structure tutorial is :%d",sizeof(t1)); return 0;}
登录后复制
输出
the size 'a' is :4the size 'b' is :4the size 'c' is :4the size 'd' is :4the size 'e' is :8the offset 'a' is :0the offset 'b' is :4the offset 'c' is :8the offset 'd' is :12the offset 'e' is :16size of the structure tutorial is :24
登录后复制
以上就是编写一个C程序来显示结构成员的大小和偏移量的详细内容,更多请关注【创想鸟】其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。
发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2585143.html