Open In App

Array within Structure in C

Last Updated : 12 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In C, a structure is a user-defined data type that allows us to combine data of different data types. While an array is a collection of elements of the same type. In this article, we will discuss the concept of an array that is declared as a member of the structure.

Array within a Structure

 An array can be declared inside a structure as a member when we need to store multiple members of the same type.

For example, suppose we have an employee and we need to store the data of his/her weekly attendance. So for that, we need to define a structure of type Employee and store the data within that. However, declaring and handling the 7 variables for each day of the week is not an easy task.

struct Employee {
    int day1, day2, day3, day4, day5, day6, day7;
};

For that, we can define an array within the structure whose data type will be int so that will be easily manageable.

Syntax to Declare Array Within Structure

The below syntax is to declare array within structure in C.

struct StructureName {     
// Other members
dataType arrayName[arraySize];
 };

Note: It is recommended to define the array as the last member function so that if it overflows, it does not overwrite all the other members.

Initialize Array Within Structure in C

We can initialize the array within structures using the below syntax:

struct StructureName variableName = { ...
{element1_value1, element1_value2 ...} };

Accessing Elements of an Array within a Structure

We can access the elements of the array within the structure using the dot (.) operator along with the array index inside array subscript operator.

structureName.arrayName[index]

Example of Array within Structure in C

The below example demonstrates how we can initialize and use the array within structure in C.

C
// C program to demonstrate the array within structures

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

// Defining array within structure
struct Employee {

    // character array to store name of the employee
    char Name[20];
    int employeeID;
    // integer array to maintain the record of attendanc eof
    // the employee
    int WeekAttendence[7];
};

int main()
{
    // defining structure of type Employee
    struct Employee emp;

    // adding data
    emp.employeeID = 1;
    strcpy(emp.Name, "Rohit");
    int week;
    for (week = 0; week < 7; week++) {
        int attendence;
        emp.WeekAttendence[week] = week;
    }
    printf("\n");

    // printing the data
    printf("Emplyee ID: %d - Employee Name: %s\n",
           emp.employeeID, emp.Name);
    printf("Attendence\n");
    for (week = 0; week < 7; week++) {
        printf("%d ", emp.WeekAttendence[week]);
    }
    printf("\n");

    return 0;
}

Output
Emplyee ID: 1 - Employee Name: Rohit
Attendence
0 1 2 3 4 5 6 




Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads