ADVERTISEMENT
ADVERTISEMENT

What is Array within Structure in C?

In C programming, an array within a structure is defined as a collection of variables of the same data type. You can declare array variable as a member of structure.

The syntax for defining an array within a structure is as follows:

struct struct_name 
{
data_type array_name[size];
};

For example, the following structure definition creates a structure named "Student" that contains an array of integers named "marks" with a size of 5:

struct Student
{
int marks[5];
};

You can also initialize the array inside the structure while defining the structure like:

struct Student
{
    int marks[5]={10,20,30,40,50};
};

Here's a simple C program that demonstrates the use of an array within a structure:

#include <stdio.h>
struct Student
{
    int marks[5];
    char name[20];
};

int main() 
{
    struct Student s1;
    printf("Enter student name: ");
    scanf("%s", s1.name);

    printf("Enter 5 marks: ");
    for (int i = 0; i < 5; i++) 
    {
        scanf("%d", &s1.marks[i]);
    }

    printf("Student details:");
    printf("Name: %s", s1.name);
    printf("Marks: ");
    for (int i = 0; i < 5; i++) 
    {
        printf("%d ", s1.marks[i]);
    }

    return 0;
}

In this program, a structure named "Student" is defined that contains two members: an array of integers named "marks" and a character array named "name". In the main function, a variable of type "Student" named "s1" is declared and its members are assigned values using the scanf function. The program then displays the student's name and marks using the printf function.

This program prompts the user to enter a student name and five marks, stores them in the structure variable, and then prints the entered details.


ADVERTISEMENT

ADVERTISEMENT