编写一个 C 程序来显示结构体成员的大小和偏移量
问题
编写一个 C 程序来定义结构体并显示成员变量的大小和偏移量
结构体 - 它是一组不同数据类型变量的集合,这些变量组合在一个名称下。
结构体声明的一般形式
datatype member1;
struct tagname{
datatype member2;
datatype member n;
};这里,struct - 关键字
tagname - 指定结构体的名称
member1, member2 - 指定构成结构体的数据项。
示例
struct book{
int pages;
char author [30];
float price;
};结构体变量
有三种声明结构体变量的方法 -
方法 1
struct book{
int pages;
char author[30];
float price;
}b;方法 2
struct{
int pages;
char author[30];
float price;
}b;方法 3
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;方法 4(使用 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<stdio.h>
#include<stddef.h>
struct 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 :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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP