DEV Community


Posted on

Structures in C


As covered in the previous post, structures are very useful for logically grouping related elements together. This can be further extended by combining them with arrays. Since structures are a type, it is perfectly valid in C to create an array of structures. So, if you had to keep track of many dates (to continue with the previous examples), an array could be created to hold all of them in one place.

Declaring an array of structures

To declare an array of structures, the syntax is similar to declaring as any other array, but preceded by the struct keyword and struct type:

// declares an array of ten items of structure type date
struct date myDates[10]
Enter fullscreen mode Exit fullscreen mode

To access or assign elements inside the array, use the index and the dot notation:

myDates[1].month = 7;
myDates[1].day = 9;
myDates.year = 1979;
Enter fullscreen mode Exit fullscreen mode

Initializing of arrays containing structures is similar to initializing multidimensional arrays. The internal curly brackets below are optional, but they make the code much more readable, so are recommended:

struct date myDates[3] =
  {7, 9, 1979},
  {11, 26, 2019},
  {12, 26, 2019},

  // to initialize values besides the one declared in the initial initialization, the curly brackets can be used inside the declaration
struct date myDates[3] =
  [4] = {1, 1, 2020}

// ...and dot notation can be used to assign specific elements as well
struct date myDates[3] = {[1].month = 12, [1].day =30};
Enter fullscreen mode Exit fullscreen mode
Structures that contain arrays

It is also possible to define structures that contain arrays as members. The most common use case of this is to have strings inside a structure, e.g. creating a structure named 'month' that contains both the number of days and the abbreviation for the name of the month:

struct month
  int numberOfDays;
  char name[3];

struct month aMonth;
aMonth.numberOfDays = 31;[0] = 'J';[1] = 'a';[2] = 'n';

// a quicker way to do the above for the name would be to use a shortcut
struct month aMonth = {31, {'J', 'a', 'n'}};
Enter fullscreen mode Exit fullscreen mode

Top comments (0)