首页  >  文章  >  后端开发  >  编写一个C程序来显示结构成员的大小和偏移量

编写一个C程序来显示结构成员的大小和偏移量

WBOY
WBOY转载
2023-08-29 20:09:19670浏览

编写一个C程序来显示结构成员的大小和偏移量

问题

编写一个C程序来定义结构体并显示成员变量的大小和偏移量

结构体 - 它是一个不同数据类型变量的集合,组合在一个名称下。

结构声明的一般形式

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<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 &#39;a&#39; is :%d</p><p>",sizeof(t1.a));
   printf("the size &#39;b&#39; is :%d</p><p>",sizeof(t1.b));
   printf("the size &#39;c&#39; is :%d</p><p>",sizeof(t1.c));
   printf("the size &#39;d&#39; is :%d</p><p>",sizeof(t1.d));
   printf("the size &#39;e&#39; is :%d</p><p>",sizeof(t1.e));
   printf("the offset &#39;a&#39; is :%d</p><p>",offsetof(struct tutorial,a));
   printf("the offset &#39;b&#39; is :%d</p><p>",offsetof(struct tutorial,b));
   printf("the offset &#39;c&#39; is :%d</p><p>",offsetof(struct tutorial,c));
   printf("the offset &#39;d&#39; is :%d</p><p>",offsetof(struct tutorial,d));
   printf("the offset &#39;e&#39; is :%d</p><p></p><p>",offsetof(struct tutorial,e));
   printf("size of the structure tutorial is :%d",sizeof(t1));
   return 0;
}

输出

the size &#39;a&#39; is :4
the size &#39;b&#39; is :4
the size &#39;c&#39; is :4
the size &#39;d&#39; is :4
the size &#39;e&#39; is :8
the offset &#39;a&#39; is :0
the offset &#39;b&#39; is :4
the offset &#39;c&#39; is :8
the offset &#39;d&#39; is :12
the offset &#39;e&#39; is :16

size of the structure tutorial is :24

以上是编写一个C程序来显示结构成员的大小和偏移量的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文转载于:tutorialspoint.com。如有侵权,请联系admin@php.cn删除