編寫一個 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

更新於: 2021-03-06

803 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告