Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

I've seen some C code that creates a structure and within the structure there are a number of arrays. Some of those arrays are of size one. So why bother making it an array? Why not just a single int?

I'm talking about something like this:

struct Foo
{

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


};

Why not make it just

struct Foo
{

uint8_t Bar;
uint32_t BigBar[4];

};
like image 655
DiBosco Avatar asked Oct 23 '25 14:10

DiBosco


2 Answers

The answer is that it is good programming habit to do so from two reasons:

  1. In case the programmer decides to change the Bar into an array at some point, there is not a lot of code changing. All needed to be done is to change the constant from 1 to ARRAY_SIZE (it is even better to have the constant defined as one actually)

  2. Using fields which are constructed the same are less prone to mistakes than fields which are different. Thinking programmers are ones who make mistakes :)

Cheers

like image 124
nerez Avatar answered Oct 25 '25 05:10

nerez


My guess is for an easier return of a pointer:

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

if you will want to use it as a pointer you would be able to pass Bar instead of &Bar if it was an int

if I had an instance of the struct defined: struct Foo aaa;

you would be able to define:

int *pInt = aaaa.Bar;

instead of:

int *pInt = &(aaaa.Bar);
like image 31
antonpuz Avatar answered Oct 25 '25 05:10

antonpuz