0
0
Cprogramming~5 mins

Defining structures

Choose your learning style9 modes available
Introduction

Structures let you group different pieces of information together under one name. This helps keep related data organized.

When you want to store information about a person, like name, age, and height.
When you need to keep details about a book, such as title, author, and pages.
When you want to group coordinates like x, y, and z in one place.
When you want to pass multiple related values to a function easily.
When you want to create a simple database record with different fields.
Syntax
C
struct StructureName {
    dataType member1;
    dataType member2;
    // more members
};

Use the keyword struct followed by a name and curly braces.

Each member inside has a type and a name, separated by semicolons.

Examples
This defines a structure named Person with a name and age.
C
struct Person {
    char name[50];
    int age;
};
A simple structure to hold 2D coordinates.
C
struct Point {
    int x;
    int y;
};
A structure to store book details.
C
struct Book {
    char title[100];
    char author[50];
    int pages;
};
Sample Program

This program defines a Person structure, creates a variable p1, assigns values, and prints them.

C
#include <stdio.h>

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

int main() {
    struct Person p1;

    // Assign values
    snprintf(p1.name, sizeof(p1.name), "%s", "Alice");
    p1.age = 30;

    // Print values
    printf("Name: %s\n", p1.name);
    printf("Age: %d\n", p1.age);

    return 0;
}
OutputSuccess
Important Notes

Remember to use struct keyword when declaring variables unless you use typedef.

Strings in C are arrays of characters, so use char name[50]; for names.

Use functions like snprintf or strcpy to assign strings safely.

Summary

Structures group different data types under one name.

Use struct keyword to define them.

Access members with dot . operator on structure variables.