Why declare a struct that only contains an array in C?

I came across some code containing the following:

struct ABC {
    unsigned long array[MAX];
} abc;

When does it make sense to use a declaration like this?


Solution 1:

It allows you to pass the array to a function by value, or get it returned by value from a function.

Structs can be passed by value, unlike arrays which decay to a pointer in these contexts.

Solution 2:

Another advantage is that it abstracts away the size so you don't have to use [MAX] all over your code wherever you declare such an object. This could also be achieved with

typedef char ABC[MAX];

but then you have a much bigger problem: you have to be aware that ABC is an array type (even though you can't see this when you declare variables of type ABC) or else you'll get stung by the fact that ABC will mean something different in a function argument list versus in a variable declaration/definition.

One more advantage is that the struct allows you to later add more elements if you need to, without having to rewrite lots of code.

Solution 3:

You can copy a struct and return a struct from a function.

You cannot do that with an array - unless it is part of a struct!

Solution 4:

You can copy it like this.

struct ABC a, b;
........
a = b;

For an array you would need to use memcpy function or a loop to assign each element.

Solution 5:

You can use struct to make a new type of data like string. you can define :

struct String {
    char Char[MAX];
};

or you can create a List of data that you can use it by argument of functions or return it in your methods. The struct is more flexible than an array, because it can support some operators like = and you can define some methods in it.

Hope it is useful for you :)