Why declare a struct that only contains an array in C?
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.
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.
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!