What is the point of creating an array of size 1?

I've seen some C code that creates a structure and there are several arrays inside the structure. Some of these arrays are one size. So why bother creating an array? Why not just one int?

I'm talking about something like this:

struct Foo
{

uint8_t Bar[1];
uint32_t BigBar[4];


};

      

Why not make it simple

struct Foo
{

uint8_t Bar;
uint32_t BigBar[4];

};

      

+3


source to share


3 answers


The answer is that it's a good programming habit to do this for two reasons:

  • In case the programmer decides to change the panel into an array at some point, no code changes are made. All one has to do is change the constant from 1 to ARRAY_SIZE (even better to have the constant defined as actually)

  • Using fields that are constructed the same way is less error prone than fields that are different. The mindset of programmers is those who make mistakes :)



Greetings

+3


source


My guess is for an easier pointer return:

it will be easier to return a pointer to a variable: Bar

if you want to use it as a pointer you can pass Bar instead &Bar

if it was an int

if I had an instance of a certain structure: struct Foo aaa;



you could define:

int *pInt = aaaa.Bar;

      

instead:

int *pInt = &(aaaa.Bar);

      

+1


source


Consistency with other frameworks?

struct alien {
    int heads[3];
    ...
};

struct human {
    int heads[1];
    ...
};

      

+1


source







All Articles