C प्रोग्रामिंग भाषा में, एक स्ट्रक्चर विभिन्न डेटाटाइप वेरिएबल्स का संग्रह है, जिन्हें एक ही नाम के तहत समूहीकृत किया जाता है।
स्ट्रक्चर्स की घोषणा और इनिशियलाइज़ेशन
स्ट्रक्चर घोषणा का सामान्य रूप निम्नलिखित है:
डेटाटाइप member1;
struct tagname {
डेटाटाइप member2;
डेटाटाइप 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;
दूसरा तरीका
struct {
int pages;
char author[30];
float price;
} b;
तीसरा तरीका
struct book {
int pages;
char author[30];
float price;
};
struct book b;
स्ट्रक्चर्स का इनिशियलाइज़ेशन और एक्सेस करना
एक मेंबर और एक स्ट्रक्चर वेरिएबल के बीच लिंक मेंबर ऑपरेटर (या डॉट ऑपरेटर) का उपयोग करके स्थापित किया जाता है।
इनिशियलाइज़ेशन निम्नलिखित तरीकों से किया जा सकता है:
पहला तरीका
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;
उदाहरण
स्ट्रक्चर वेरिएबल्स की तुलना के लिए C प्रोग्राम:
struct class {
int number;
char name[20];
float marks;
};
main() {
int x;
struct class student1 = {001, "Hari", 172.50};
struct class student2 = {002, "Bobby", 167.00};
struct class student3;
student3 = student2;
x = ((student3.number == student2.number) &&
(student3.marks == student2.marks)) ? 1 : 0;
if(x == 1) {
printf("\nstudent2 और student3 समान हैं\n\n");
printf("%d %s %f\n", student3.number,
student3.name,
student3.marks);
} else
printf("\nstudent2 और student3 अलग हैं\n\n");
}
आउटपुट
student2 और student3 समान हैं 2 Bobby 167.000000