Page Content

Tutorials

What Is The Structures In C, How To Create & Initialize It?

Structures In C

One of C’s most useful features is its structures, which let you combine variables of various kinds under one name. Arrays, on the other hand, are collections of identically typed data elements. Like a record in a database table, a structure offers a practical way to group relevant information together. You can make your own unique (user-defined) data type by specifying a structure. According to the C standard, structures are referred to as aggregates.

This is a summary of C structures derived from the references given:

Defining Structures

The struct keyword is used to define a structure. An optional structure tag name comes after the struct keyword. After the tag name, variables, also known as members, are declared inside a pair of braces {}. Within that particular structural type, each member needs to have a unique name. A semicolon (;) must be used to conclude the entire structure specification.

The ‘shape’ or template of a structure is defined by a structure definition, which does not instruct the compiler to set aside any memory.

Creating Structure Variables

Once a structural type has been defined, variables of that type can be declared. The struct keyword, structure tag, and variable name(s) can be used to do this:

struct variable_name structure_tag;

As an alternative, you can merge the variable declaration and structure definition:

Accessing Structure Members

You can access each member of a structure variable after it has been formed.

  • Use the dot operator (.) if you have a structural variable.
  • The arrow operator (->) is used when you have a pointer to a structure.

The operators. and -> have a high priority. By explicitly dereferencing the pointer first, such as in (*pointer.member), you can also access members via a pointer.

Example:

#include <stdio.h>
#include <string.h> // For strcpy
struct student {
    int roll_no;
    char name[17];
    float percentage;
};
int main(void) {
    struct student s1; // Structure variable
    struct student *s1_ptr = &s1; // Pointer to the structure variable
    // Accessing members using the dot operator (.) with the variable s1
    s1.roll_no = 101;
    strcpy(s1.name, "Alice"); // Using strcpy for strings
    s1.percentage = 85.5;
    // Accessing members using the arrow operator (->) with the pointer s1_ptr
    printf("Student Roll No: %d\n", s1_ptr->roll_no);
    printf("Student Name: %s\n", s1_ptr->name);
    printf("Student Percentage: %.2f\n", s1_ptr->percentage);
    // Equivalently accessing using dereferencing with the pointer
    printf("Student Roll No (via dereference): %d\n", (*s1_ptr).roll_no);
    return 0;
}

Output:

Student Roll No: 101
Student Name: Alice
Student Percentage: 85.50
Student Roll No (via dereference): 101

Initializing Structures

An initializer list surrounded in braces {} can be used to initialize structure variables at the time of declaration. In the order in which they are declared, the values in the list match the members.

The values in the initialiser list must be constant expressions for structure variables that are not automated (such as global or static). The number of initialisers can be less than the number of members.

Array of Structures

Arrays with each element being a structure can be declared. Information about several entities with the same structure can be stored in this way.

Structures Containing Structures and Pointers

Nested structures are those that have other structures as members. They may also reference self-referential structures, which are their own kind. Pointers are needed to build dynamic data structures like linked lists, queues, stacks, and trees.

Examples:

#include <stdio.h>
// Nested structure example
struct date { // Define date structure
    int dd, mm, yy;
};
struct employee { // Define employee structure
    int emp_code;
    char name[17];
    struct date dob; // Member is a date structure
    float salary;
};
// Self-referential structure example (for linked lists)
struct entry {
    int value;
    struct entry *next; // Pointer to another struct entry
};
int main(void) {
    struct employee emp1;
    struct entry node1, node2;
    // Accessing nested structure members
    emp1.dob.dd = 15;
    emp1.dob.mm = 7;
    emp1.dob.yy = 2000;
    // Example usage of self-referential structure (simplified linked list nodes)
    node1.value = 100;
    node1.next = &node2; // node1 points to node2
    node2.value = 200;
    node2.next = NULL; // node2 is the last node
    printf("Employee DOB: %d/%d/%d\n", emp1.dob.dd, emp1.dob.mm, emp1.dob.yy);
    printf("Node1 value: %d\n", node1.value);
    printf("Node2 value: %d\n", node1.next->value); // Access node2 via node1's pointer
    return 0;
}

Output:

Employee DOB: 15/7/2000
Node1 value: 100
Node2 value: 200

Using Structures with Functions

Functions can be passed structures. They can be passed by reference (providing a pointer to the structure) or by value (making a copy). The function must pass via reference (using a pointer) if it needs to change the original structural variable. Structures can also be returned by functions.

Other Operations

The assignment operator = can be used to transfer the value of one structural variable to another of the same type. The & operator can also be used to retrieve the address of a structure variable or any of its members. Nevertheless, the == and!= operators cannot be used to directly compare structures.

It is common practice to define records for file processing using structures. Classes in C++ are based on the idea of C structures and extend structures by adding functions and data. Declarations can be made more readable by using typedef to define aliases for structural types.

You can also read What Is C Arrays Of Function Pointers With Code Examples

Agarapu Geetha
Agarapu Geetha
My name is Agarapu Geetha, a B.Com graduate with a strong passion for technology and innovation. I work as a content writer at Govindhtech, where I dedicate myself to exploring and publishing the latest updates in the world of tech.
Index