Home > Article > Backend Development > Write a C program to display the size and offset of structure members
Write a C program to define a structure and display the size and offset of member variables
Structure Body - It is a collection of variables of different data types, grouped under one name.
datatype member1; struct tagname{ datatype member2; datatype member n; };
Here, struct - keyword
tagname - specifies the name of the structure
member1, member2 - specifies the constituent structure data items.
struct book{ int pages; char author [30]; float price; };
There are three ways to declare structure variables-
struct book{ int pages; char author[30]; float price; }b;
struct{ int pages; char author[30]; float price; }b;
struct book{ int pages; char author[30]; float price; }; struct book b;
The link between members and structure variables is established through the member operator (or dot operator).
Can be initialized in the following ways:
struct book{ int pages; char author[30]; float price; } b = {100, "balu", 325.75};
struct book{ int pages; char author[30]; float price; }; struct book b = {100, "balu", 325.75};
struct book{ int pages; char author[30]; float price; } ; struct book b; b. pages = 100; strcpy (b.author, "balu"); b.price = 325.75;
struct book{ int pages; char author[30]; float price; } ; struct book b; scanf ("%d", &b.pages); scanf ("%s", b.author); scanf ("%f", &b. price);
Declare the structure using data members and try to print their offset values and the size of the structure.
Real-time demonstration
#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</p><p>",sizeof(t1.a)); printf("the size 'b' is :%d</p><p>",sizeof(t1.b)); printf("the size 'c' is :%d</p><p>",sizeof(t1.c)); printf("the size 'd' is :%d</p><p>",sizeof(t1.d)); printf("the size 'e' is :%d</p><p>",sizeof(t1.e)); printf("the offset 'a' is :%d</p><p>",offsetof(struct tutorial,a)); printf("the offset 'b' is :%d</p><p>",offsetof(struct tutorial,b)); printf("the offset 'c' is :%d</p><p>",offsetof(struct tutorial,c)); printf("the offset 'd' is :%d</p><p>",offsetof(struct tutorial,d)); printf("the offset 'e' is :%d</p><p></p><p>",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
The above is the detailed content of Write a C program to display the size and offset of structure members. For more information, please follow other related articles on the PHP Chinese website!