Skip to content
doubtly

1 answer

Best answer

Answer: An array is a collection of elements of the same data type accessed by an index, while a structure is a collection of members of different data types accessed by name.

Sr. No.PointArrayStructure
1DefinitionCollection of elements of the same data type.Collection of members that may be of different data types.
2Declarationint marks[5];struct student { int roll; char grade; float marks; };
3AccessBy index: marks[0], marks[1] … (index starts at 0).By member name with the dot operator: s.roll, s.marks (or -> with a pointer).
4MemoryElements stored in contiguous locations; size = number of elements × size of one element.Members stored one after another in declaration order; size is at least the sum of member sizes (the compiler may add padding).
5KeywordNo keyword; uses [ ].Uses the keyword struct.
6NameThe array name gives the address of the first element (array name acts like a pointer).The structure variable name refers to the whole record; its address is taken with &.
7AssignmentOne array cannot be assigned to another with =.One structure variable can be assigned to another of the same type with =.
8TypeDerived data type.User-defined data type.

Both can be combined: an array of structures (struct student s[60];) or a structure containing an array (char name[20]; as a member).

Example:

#include <stdio.h>

struct student
{
    int roll;
    char grade;
    float marks;
};

int main()
{
    int a[3] = {10, 20, 30};                 /* array: same type, index access */
    struct student s = {1, 'A', 87.5};       /* structure: different types, name access */

    printf("a[1] = %d\n", a[1]);
    printf("Roll = %d, Grade = %c, Marks = %.1f\n", s.roll, s.grade, s.marks);
    printf("sizeof(a) = %zu, sizeof(s) = %zu\n", sizeof(a), sizeof(s));
    return 0;
}

Output (actual run, gcc 64-bit):

a[1] = 20
Roll = 1, Grade = A, Marks = 87.5
sizeof(a) = 12, sizeof(s) = 12

Here sizeof(s) is 12 rather than 4 + 1 + 4 = 9 because the compiler adds padding after grade.

Doubtly · 11 Jun 2022 Report
Was this answer helpful?

Your answer

Log in or create a free account to answer this question.