Use of Structure in C

Array of Structure

An array of structures is a data structure that contains multiple instances of a composite data type called a structure, where each instance (element) of the array is itself a structure. This allows for organizing related pieces of data into a single entity, making it easier to manage and manipulate them.

For example, consider a structure representing rool number of 100 student.

Example
struct student
{
   int roll_number[100];
}st1;
So it contains 100 memory space for containing the 100 integer type data.

Value assign and access in the array

let us soppose in previous example we define the array in structure here we assigning some values.

Example
st1.rool_number[0]=193281361;

Here we are assign the value in index zero of an array.
we can also access as same manner if we want to acess thid value then use simply:
st1.rool_number[0];
It return the value store in 0th position in array of st1.

Use of pointer in structure

We have already learned about pointers, which hold the address of another variable. Similarly, here we'll learn about pointers in structures.

Example
struct student{
   char name[20];
    int roll_number;
};
struct student st1;
struct student *ptr;
ptr=&st1;
Here 'ptr' pointer variable points to structure variable st1. 

Assigning the value to member of structure

If we want to assigning value to the member of pointer structure variable then use (->) operator.

Example
ptr->name="vikas";
ptr->roll_number=183481361;

Access the member of structure variable

If we want to access the member of pointer structure variable then use (->) operator.

Example
ptr->name;
ptr->roll_number;
It will return "vikas" and 2nd one is "193281361".	   

Structure Using function

We have learned about passing structure variables as arguments and returning structure variables from functions. Passing a structure variable as an argument is similar to passing any other variable, but the data type changes to the structure's definition. For instance, if we pass a structure variable named st1 to a function called std(), the function definition would include the structure as an argument.

Syntax
function_name(struct student st1){}
Example
#include<stdio.h>
struct student
{
    char name[10];
    int roll_no;
}; 
void display(struct student st2)
{
    printf("%s", st2.name);
    printf("%d\n", st2.roll_no);
}
int main( )
{
    struct student st1;
    printf("Enter the student name:");
    scanf("%s", &st1.name);
    printf("Enter the student Roll Number:");
    scanf("%d", &st1.roll_no);
    display(st1);
    return 0;
}