Skip to content

[C] Introduction of Structures

Last Updated on 2021-04-30 by Clay

A structure is a type that stores multiple related variables (variables that may contain multiple different data types) under one-name for easy control.

In C programming language, we can declare a structure by keyword struct:

struct struct-name {
    data-type variable_1;
    data-type variable_2;
    ...
} v1, v2, ..., vn;

How to use structure

c_struct_example_01
#include <stdio.h>


struct point {
    int x;
    int y;
};


// Main
int main() {
    struct point a = {-1, -1};
    struct point b = {2, 3};

    return 0;
}


This way is of course possible. But if the properties of structure are modified in the future, then our variable declaration will have to modify the code along with it.

#include <stdio.h>


struct point {
    int x;
    int y;
};


// Main
int main() {
    struct point a = {
        .x = -1,
        .y = -1
    };

    struct point b = {
        .x = 2,
        .y = 3
    };

    return 0;
}


We can even simplify it a little bit, and use typedef to simplify the declaration of variables in the structure.

#include <stdio.h>


typedef struct point point;


struct point {
    int x;
    int y;
};


// Main
int main() {
    point a = {
        .x = -1,
        .y = -1
    };

    point b = {
        .x = 2,
        .y = 3
    };

    return 0;
}

The structure also declare the structure.

c_struct_example_01


#include <stdio.h>


// TYPEDEF
typedef struct point point;
typedef struct rect rect;


// STRUCT
struct point {
    int x;
    int y;
};

struct rect {
    point a;
    point b;
};


// Main
int main() {
    // Init
    point a = {
        .x = -1,
        .y = -1
    };

    point b = {
        .x = 2,
        .y = 3
    };

    // Rect
    rect area = {
        .a = a,
        .b = b
    };

    return 0;
}



Structure and Function

If you want to define a function and return our custom structure, you can refer the following sample code:

#include <stdio.h>


// TYPEDEF & STRUCT
typedef struct point {
    int x;
    int y;
} point;

typedef struct rect {
    point a;
    point b;
} rect;



rect getRect(point a, point b) {
    rect area = {
        .a = a,
        .b = b
    };

    return area;
}




// Main
int main() {
    // Init
    point a = {
        .x = -1,
        .y = -1
    };

    point b = {
        .x = 2,
        .y = 3
    };

    // Rect
    rect area = getRect(a, b);
    printf("area.a: (%d, %d)\n", area.a.x, area.a.y);
    printf("area.b: (%d, %d)\n", area.b.x, area.b.y);

    return 0;
}


Output:

area.a: (-1, -1)
area.b: (2, 3)

References


Read More

Leave a Reply