Search code examples
carraysmultidimensional-arraystructdimensions

Why should you use a 2D array of structs?


I`m curious about if there are cases to use a 2D array of structures, like f.e.:

typedef struct
{
 //member variables
}myStruct;

myStruct array2D[x][y]; 
//Uses cases of array2D[x][y]? Do we need them?

Why should you use a 2D array of structs?


Solution

  • Why should you use a 2D array of structs?

    A defined structure is basically just a type like any other (though of course, any type is different from the other and there is a difference between private and standard datatypes; not even mentioning the differences in memory allocation between objects of that types) with which you can declare objects.

    You could also ask: Why should you use a char,int or double two-dimensional array?

    It is not only a structure own kind of thing.

    It depends on the context and its worth to have a clear "structure" in ones code; So to code in this way can help you to make your code more readable and clear, if you need a huge amount of objects of a certain type, in this case a structure.

    Maybe you even want to group some objects and/or want to treat them differently. In this case, multiple array dimensions are beneficial because you can address objects of each dimension explicitly and separately.

    As @buysbee mentioned in the comments:

    One obvious example, where it is beneficial to store structure objects in a two-dimensional array is to storing the pixels of a picture. It is better to store the "pixel" structure objects in a two-dimensional array because this emulates how a picture is constructed of naturally.