Skip to main content

Arrays within structures

Short answer

A structure member can be an array (e.g., int marks[3]). Elements are accessed as s.marks[i]. Initialization uses nested braces like {70,82,64}. Copying the structure copies the entire array inside it.

Explain about "Arrays within structures" along with programming example.

A structure member can itself be an array. The array may be of characters (a string such as name[20]) or of numbers (such as marks of several subjects). This groups all the values related to one entity.

struct student {
    char name[20];
    int roll;
    int marks[3];           /* array within the structure */
};

Individual elements are reached with the dot and then the index: s.marks[1]. The array can be initialised in nested braces: {"Sita", 5, {70, 82, 64}}. Copying the structure also copies the array inside it.

#include <stdio.h>

struct student {
    char name[20];
    int roll;
    int marks[3];            /* array inside a structure */
};

int main(void)
{
    struct student s = {"Sita", 5, {70, 82, 64}};
    int total = 0;

    for (int i = 0; i < 3; i++)
        total += s.marks[i];
    printf("Name: %s  Roll: %d\n", s.name, s.roll);
    printf("Marks: %d %d %d  Total = %d  Percentage = %.2f\n",
           s.marks[0], s.marks[1], s.marks[2], total, total / 3.0);
    return 0;
}

Output:

Name: Sita  Roll: 5
Marks: 70 82 64  Total = 216  Percentage = 72.00

✓ Answer checked by Claude Opus 5.5 (high effort)

All Computer Programming chapter 8 questions →