Structure
Structure एक derived data type हैं c programming में, जो कि एक ही बार में एक या एक से अधिक प्रकार की values को रख सकता है, जैसे की array एक बार में अधिक values को रख सकता है लेकिन वह values सामान प्रकार की होती है, structure में dono प्रकार की हो सकती है।
- structure values को contiguous मेमोरी लोकेशन में store करता है, एक-के-बाद एक।
- Structure की मदद से हम different data types को एक single variable में समूहित कर सकते है।
- एक structure को declare करने के लिए
struct
keyword का उपयोग किया जाता है।
Declaring a Structure
struct structure_name { data_type variable_name; data_type variable_name; ... };
उदाहरण के लिए, यहाँ पर एक structure एक structure disclare किया है जो कि Student है, इस structure की अंदर name एवं age दो variable है, जिन्हे structure members भी कहते है –
struct Student { char *name; int age; };
Declaring a Structure Variable
structure variable को declare करने के लिए निन्म syntax को follow करना होगा –
struct structure_name variable_name;
उदाहरण के लिए, यहाँ पर एक Student structure का एक structure variable s1 declare किया गया है।
int main() { struct Student s1; return 0; }
Accessing Structure Members
Structure के members को access करने की लिए . (dot operator) का उपयोग किया जाता है, यदि structure variable, pointer variable declare नहीं है तो, यदि structure variable, pointer variable declare है तो -> (arrow operator) का उपयोग किया जायेगा।
int main() { struct Student s1; // assign name to student s1 s1.name = "Rahul"; // assign age to student s1 s1.age = 21; // print student s1 information printf("Student name is : %s\n", s1.name); printf("Student age is : %d\n", s1.age); return 0; }
Complete Example (dot operator)
#include <stdio.h> struct Student { char *name; int age; }; int main() { struct Student s1; // assign name to student s1 s1.name = "Rahul"; // assign age to student s1 s1.age = 21; // print student s1 information printf("Student name is : %s\n", s1.name); printf("Student age is : %d\n", s1.age); return 0; } // -------output------------- Student name is : Rahul Student age is : 21
Complete Example (arrow operator)
#include <stdio.h> #include <stdlib.h> struct Student { char *name; int age; }; int main() { // dynamic memory allocation struct Student *s1 = (struct Student*)malloc(sizeof(struct Student)); // assign name to student s1 s1->name = "Rahul"; // assign age to student s1 s1->age = 21; // print student s1 information printf("Student name is: %s\n", s1->name); printf("Student age is: %d\n", s1->age); return 0; } // -------output------------- Student name is : Rahul Student age is : 21