Structures in C

Understanding structures and their usage in C programming

What are Structures?

A structure is a user-defined data type that allows you to combine data items of different kinds. Structures are used to represent a record.

Structures Kya Hote Hain? (Hinglish)

Structure ek user-defined data type hota hai jo different types ke data items ko combine karne ki permission deta hai. Structures ka use records ko represent karne ke liye kiya jata hai.

Structure Syntax

// Structure definition
struct Student {
    char name[50];
    int roll;
    float marks;
};

// Structure variable declaration
struct Student s1;
                    

Example Program

#include 
#include 

// Structure definition
struct Student {
    char name[50];
    int roll;
    float marks;
};

int main() {
    // Structure variable declaration and initialization
    struct Student s1 = {"John", 101, 85.5};
    
    // Accessing structure members
    printf("Student Name: %s\n", s1.name);
    printf("Roll Number: %d\n", s1.roll);
    printf("Marks: %.1f\n", s1.marks);
    
    // Structure array
    struct Student class[3] = {
        {"Alice", 102, 90.0},
        {"Bob", 103, 75.5},
        {"Charlie", 104, 88.0}
    };
    
    // Accessing structure array elements
    printf("\nClass Details:\n");
    for(int i = 0; i < 3; i++) {
        printf("Student %d: %s, Roll: %d, Marks: %.1f\n",
               i+1, class[i].name, class[i].roll, class[i].marks);
    }
    
    return 0;
}
                    

Program Explanation (Hinglish)

Is program mein structure ka use kiya gaya hai:

  • Student structure: name, roll number aur marks store kar raha hai
  • Single student: s1 variable mein ek student ka data store hai
  • Multiple students: class array mein 3 students ka data store hai

Important Points

  • Structures can contain different data types
  • Structure members are accessed using dot (.) operator
  • Structures can be passed to functions
  • Structures can contain other structures
  • Structure size is sum of all member sizes