HOME HTML EDITOR C JAVA PHP

C Structures: Creating Custom Data Types

A **Struct** is a collection of variables (called "members" or "fields") that can be of different data types. Structures are used to represent real-world entities like a Student, a Product, or a Point in a 2D plane.

1. Defining and Declaring a Struct

To use a structure, you must first define its template using the struct keyword. This tells the compiler what the "package" looks like.

// Defining a structure template
struct Student {
    int id;
    char name[50];
    float gpa;
};

int main() {
    // Declaring a variable of type 'struct Student'
    struct Student s1;
    return 0;
}

2. Accessing Struct Members

To access or assign values to the members of a structure, we use the **Dot Operator** (.).

struct Student s1;

s1.id = 101;
s1.gpa = 3.8;
strcpy(s1.name, "Alice"); // Use strcpy for strings!

printf("Student Name: %s", s1.name);

3. Initializing Structs

You can initialize a struct in a single line, similar to an array, by placing values in curly braces in the same order they were defined.

struct Student s2 = {102, "Bob", 3.5};

4. Copying Structures

One of the best features of structs is that you can copy all the data from one struct to another using a simple assignment operator (=), which isn't possible with arrays.

struct Student s3;
s3 = s2; // Now s3 has all the same data as s2

5. Nested Structures

A structure can also contain another structure as one of its members. This is useful for complex data, like a Person having an Address.

struct Address {
    char city[20];
    int pin;
};

struct Person {
    char name[20];
    struct Address addr; // Nested struct
};

6. Comparison: Structs vs. Arrays

Feature Array Structure
Data Types Homogeneous (All same) Heterogeneous (Different)
Access Method Index number [0] Member name (.id)
Assignment Cannot use = for full array Can use = to copy all data
Pro Tip: To make your code cleaner, use the typedef keyword with structs. This allows you to write Student s1; instead of struct Student s1; every time.