Explain the concept of an array within a structure in C programming

An array within a structure in C programming is a powerful feature that allows you to group related data elements together. When you declare an array as a member of a structure, you can store multiple values of the same data type within a single structure variable.

Syntax

struct structure_name {
    datatype member1;
    datatype array_name[size];
    datatype member2;
};

General Structure Declaration

The basic syntax for declaring a structure is −

struct tagname {
    datatype member1;
    datatype member2;
    datatype member_n;
};

Here, struct is the keyword, tagname specifies the name of structure, and member1, member2 are the data items that make up the structure.

Example 1: Simple Structure with Array

Here's a basic example of a structure containing an array −

struct book {
    int pages;
    char author[30];
    float price;
};

In this example, author is a character array that can store up to 30 characters.

Example 2: Complete Program with Array in Structure

The following program demonstrates how to use an array within a structure −

#include <stdio.h>

/* Declaration of the structure candidate */
struct candidate {
    int roll_no;
    char grade;
    /* Array within the structure */
    float marks[4];
};

/* Function to display the content of the structure variables */
void display(struct candidate a1) {
    printf("Roll number : %d
", a1.roll_no); printf("Grade : %c
", a1.grade); printf("Marks secured:
"); int i; int len = sizeof(a1.marks) / sizeof(float); /* Accessing the contents of the array within the structure */ for (i = 0; i < len; i++) { printf("Subject %d : %.2f
", i + 1, a1.marks[i]); } } int main() { /* Initialize a structure */ struct candidate A = {1, 'A', {98.5, 77, 89, 78.5}}; /* Function to display structure */ display(A); return 0; }
Roll number : 1
Grade : A
Marks secured:
Subject 1 : 98.50
Subject 2 : 77.00
Subject 3 : 89.00
Subject 4 : 78.50

Key Points

  • Arrays within structures are accessed using the dot operator followed by array indexing: structure_variable.array_name[index]
  • The array size must be specified during structure declaration
  • Structure initialization can include array initialization using curly braces
  • Arrays in structures are stored contiguously in memory

Conclusion

Arrays within structures provide an efficient way to organize related data. This feature is particularly useful when you need to group multiple values of the same type with other data members in a single logical unit.

Updated on: 2026-03-15T13:24:55+05:30

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements