C Structures

Allows you to group together variables of different data types under a single name.

Syntax
struct struct_name {
data_type member1;
data_type member2;
// ... additional members
};

  1. struct_name - declares the name of th estructure
  2. data_type - Declare a data type i.e; int, float, char, etc...
Example
#include <stdio.h>
// Declaration of a structure
struct Point {
    int x;
    int y;
};

int main() {
    // Initialization of a structure variable
    struct Point p1 = {10, 20};
    struct Point p2;
    
    // Copying structure members
    p2 = p1;
    
    // Accessing structure members
    printf("Coordinates: (%d, %d)\n", p1.x, p1.y);
    printf("Coordinates: (%d, %d)\n", p2.x, p2.y);
    
    // Modifying structure members
    p1.x = 30;
    p1.y = 40;
    
    printf("Modified Coordinates: (%d, %d)\n", p1.x, p1.y);

    return 0;
}

The code example: At top we declare a structure Point with a data type int of variables x and y
and we initialize the structure Point p1 with values 10 and 20.
we can create another structure Point and copy from p1 tp p2
we can access by using te varibale declared in the structure at the top
we can also declare new values

Example
#include <stdio.h>
#include 

struct Date {
    int day;
    int month;
    int year;
};

struct Person {
    char name[50];
    int age;
    struct Date birthdate;
};

int main() {
    struct Person person1 = {"John Doe", 25, {15, 8, 1997}};

    printf("Person Information:\n");
    printf("Name: %s\n", person1.name);
    printf("Age: %d\n", person1.age);
    printf("Birthdate: %d/%d/%d\n", person1.birthdate.day, person1.birthdate.month, person1.birthdate.year);

    return 0;
}

Person structure contains a nested Date structure.
This allows you to represent more complex data structures.


Quick Recap - Topics Covered

C Structures

Practice With Examples in Compilers

The Concepts and codes you leart practice in Compilers till you are confident of doing on your own. A Various methods of examples, concepts, codes availble in our websites. Don't know where to start Down some code examples are given for this page topic use the code and compiler.


Example 1
Example 1 Example 2 Example 3 Example 4 Example 5


Quiz


FEEDBACK