C Structures

An array stores many values of the same type. A structure (struct) stores values of different types together. For example, a student has a name, roll number and marks.

Define and use a structure

#include <stdio.h>
#include <string.h>

struct Student {
    int roll;
    char name[30];
    float marks;
};

int main(void) {
    struct Student s1;

    s1.roll = 1;
    strcpy(s1.name, "Robin");
    s1.marks = 85.5f;

    printf("Roll: %d\n", s1.roll);
    printf("Name: %s\n", s1.name);
    printf("Marks: %.1f\n", s1.marks);
    return 0;
}

Output:

Output of the above program is

Roll: 1
Name: Robin
Marks: 85.5

We use the dot operator . to reach a member. A string member cannot be assigned with =, so we use strcpy().

Initialize at declaration

#include <stdio.h>

struct Student {
    int roll;
    char name[30];
    float marks;
};

int main(void) {
    struct Student s = {2, "Maria", 92.0f};
    struct Student t = {.roll = 3, .name = "John", .marks = 78.5f};

    printf("%d %s %.1f\n", s.roll, s.name, s.marks);
    printf("%d %s %.1f\n", t.roll, t.name, t.marks);
    return 0;
}

Output:

Output of the above program is

2 Maria 92.0
3 John 78.5

Read from the user

#include <stdio.h>

struct Point {
    int x, y;
};

int main(void) {
    struct Point p;

    scanf("%d %d", &p.x, &p.y);
    printf("Point is (%d, %d)\n", p.x, p.y);
    return 0;
}

Output:

Output of the above program is

4 9
Point is (4, 9)

Copy and pass to a function

One structure can be assigned to another. A function gets a copy when you pass it by value.

#include <stdio.h>

struct Point {
    int x, y;
};

void show(struct Point p) {
    printf("(%d, %d)\n", p.x, p.y);
}

int main(void) {
    struct Point a = {1, 2};
    struct Point b = a;       // copy

    b.x = 10;
    show(a);
    show(b);
    return 0;
}

Output:

Output of the above program is

(1, 2)
(10, 2)

Note: The size of a structure can be bigger than the sum of its members, because the compiler adds some padding bytes for alignment.

Next: C Nested Structure.


Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.