Array of structure in c


An array of structure is considered as, declaring the array of the user-defined structure variable.

Suppose we want to enter the details of 3 students. We will simply define a structure datatype and declare three user-defined structure variables of the structure data-type. But if we want to enter the details of more than 100 students, it will be difficult to declare a large number of structure variables. Also, the program will become big and complicated. 

 

There is a solution to this problem. We will simply declare the array of a user-defined structure variable.

Due to this, we can enter the number of students details as much we want.

 

This will make the program reliable and short.

 

Let us take the demo program,

 

Enter the details of five gadgets. Details are name prizes and quantity of gadgets.

 

We have defined a structure “gadgets” globally, 

prize can be a bigger number so, we took long int.

 Inside the main function, we have declared an array of structure datatype “gadgets” which is G[5]. 

Input is taken in the format as, G[i].name

 

i.e., G of ith row and its name. That means the name of the ith gadget.

 

In a string, there is no need to assign & operator to scanf, as the variable itself points to the base address, therefore to access the base address of a string, there is no need to assign & operator.

 

In the program below, we have simply taken the inputs in G[5] and printed.

 

Have a look at the program and the output.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include<stdio.h>

struct gadgets
{
 char name[10];
 long int prize;
 int quantity;
};

int main()
{
 struct gadgets G[5];  //array declaration
 int i;

 printf("Enter the name of gadgets:\n\n");
 for(i=0;i<5;i++)
 scanf("%s",G[i].name);

 printf("Enter the prize of gadgets:\n\n");
 for(i=0;i<5;i++)
 scanf("%ld",&G[i].prize);

 printf("Enter the number of guantity:\n\n");
 for(i=0;i<5;i++)
 scanf("%d",&G[i].quantity);

 printf("print all the details of gadgets:\n\n");
 printf("  name \t   prize\t quantity\n");
 for(i=0;i<5;i++)
 {
  printf("%d. %s   %ld    %d\n",i+1,G[i].name,G[i].prize,G[i].quantity);
 }
 return 0;
 }

To understand the memory allocation of the above program observe the below diagram

The numbers shown at the top of every block are the address of the memory allocation as per our consideration.

 

6000 is the base address of G[5] present at position G[0].

 

Character array requires 10bytes of memory. Hence, 10 bytes are reserved for every char array.

 

We are considering that we are using a 32bit compiler Eg. turbo c.

 

Hence, the size of the integer is 2bytes, and the long int is 4bytes.

 

array-structure-c

output:

 
array-structure-c