- 2071 Shrawan · 4 marks
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)
Related questions
- Creating 1D and 2D arrays · Computer Programming, chapter 7 · asked 2×
- Array overflow/underflow; add two arrays · Computer Programming, chapter 7
- Two dimensional arrays in FORTRAN · Computer Programming, chapter 11
- Nested structures with example · Computer Programming, chapter 8 · asked 7×
- Correct program: character arrays · Computer Programming, chapter 7
- Significance of arrays; multiply 3×3 matrices · Computer Programming, chapter 7
- T1 and E1 frame structures and bit rates · Telecommunications, chapter 3
- Roadside structures and landslide stabilisation · Transportation Engineering I, chapter 5