C documentation V1 Help

Structures Overview

Structures in C allow you to group together variables of different data types under a single name. They provide a way to represent real-world entities more effectively. Let's explore how to create and use structures:

1. Structure Definition

  • To define a structure, use the struct keyword, followed by the structure name and a list of member variables.

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

This defines a structure named Person with three members: name (a character array), age (an integer), and height (a floating-point number).

2. Structure Declaration

  • After defining a structure, you can declare variables of that type.

    struct Person person1, person2;

Here, person1 and person2 are variables of the Person structure.

3. Accessing Structure Members

  • Use the dot (.) operator to access structure members.

    strcpy(person1.name, "John Doe"); person1.age = 25; person1.height = 5.9;

4. Initializing Structures

  • Structures can be initialized during declaration.

    struct Person person3 = {"Alice Wonderland", 30, 5.5};

5. Passing Structures to Functions

  • You can pass structures to functions by value or by reference.

    void displayPerson(struct Person p) { printf("Name: %s\n", p.name); printf("Age: %d\n", p.age); printf("Height: %.2f\n", p.height); }

6. Arrays of Structures

  • You can create arrays of structures to represent a collection of entities.

    struct Person people[3] = {{"Bob Smith", 22, 6.1}, {"Eve Johnson", 28, 5.8}, {"Charlie Brown", 35, 5.11}};

7. Nested Structures

  • Structures can be nested within other structures.

    struct Address { char street[50]; char city[30]; int zipCode; }; struct Employee { char name[50]; int empID; struct Address address; };

Here, Employee structure contains another structure, Address.

Structures provide a powerful way to organize and manipulate complex data in C. They enhance code readability and maintainability by grouping related information together.

If you have specific questions or if there are additional topics you'd like to explore, feel free to ask!

Last modified: 25 February 2024