C programming structure and arrays

In the previous tutorial, we used datatypes likeĀ int, float and arrays of characters inside the structure.

Besides those C also permits the use of arrays as elementsĀ that can be one-dimensional or multi-dimensional of any type.

In this tutorial, you will learn about the association of c programming structure and arrays.

c programming structure and arrays

Example of arrays within structure

struct car_model{
  char car_name[20];
  int model[5];
} cars[3];

Here in this example model contains 5 elements model[0], model[1], model[2], model[3], model[4] and three struct variable car also has 3 elements car[0], car[1] and car[2]. Those structure elements model can be accessed as following:



Arrays of structures

In C, we can also create an array of structure variable where each element of the array will represent structure variable.

It is same like a multidimensional array with each array element holding structure variable which contains data of different datatypes.

Consider following example:

struct car{
  int carnum_1;
  int carnum_2;
int main()
  struct car numbers[2] = {{22,34},{54,88}};

In above example, we have declared an array of structure variable called numbers which contain 2 elements numbers[0] and numbers[1]. Here each element is initialized and can be accessed as following:

numbers[0].carnum_1 = 22;
numbers[1].carnum_1 = 34;
numbers[0].carnum_2 = 54;
numbers[1].carnum_2 = 86;