समस्या
स्ट्रक्चर को परिभाषित करने और मेंबर वेरिएबल्स का आकार और ऑफसेट प्रदर्शित करने के लिए 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\n", sizeof(t1.a));
printf("the size 'b' is :%d\n", sizeof(t1.b));
printf("the size 'c' is :%d\n", sizeof(t1.c));
printf("the size 'd' is :%d\n", sizeof(t1.d));
printf("the size 'e' is :%d\n", sizeof(t1.e));
printf("the offset 'a' is :%d\n", offsetof(struct tutorial, a));
printf("the offset 'b' is :%d\n", offsetof(struct tutorial, b));
printf("the offset 'c' is :%d\n", offsetof(struct tutorial, c));
printf("the offset 'd' is :%d\n", offsetof(struct tutorial, d));
printf("the offset 'e' is :%d\n\n", 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