首頁  >  文章  >  後端開發  >  寫一個C程式來顯示結構成員的大小和偏移量

寫一個C程式來顯示結構成員的大小和偏移量

WBOY
WBOY轉載
2023-08-29 20:09:19673瀏覽

寫一個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刪除