So I want to have a definition of the size of an array within a struct known at compile time. I would also like that number available as a variable for ease of use later. What I have is the following:
const int BANANA_ARRAY_SIZE = 10;
typedef struct
{
char bananas[BANANA_ARRAY_SIZE];
int some_other_stuff;
} banana_struct;
This functions fine. However, if I have it in a .h file that gets included in multiple places, the compiler complains about redefinition of BANANA_ARRAY_SIZE (which makes sense). So I need to declare it as an extern so multiple compilation units can know about it.
So, I now have
extern const int BANANA_ARRAY_SIZE;
typedef struct
{
//.. same as before
} banana_struct;
and in an implementation file I have
const int BANANA_ARRAY_SIZE = 10;
But now the compiler won't let me define the struct anymore with complaints of
fields must have a constant size: variable length array in structure
Is there any way I can achieve what I want (have length of array stored in variable and used to define struct)?
Edit:
In response to the suggestions to instead use #define
s, I'd rather not.
My question is about how to have this constant value stored in a variable and also used to set the length of an array in a struct. If you need further justification, assume I need a function that takes a pointer to an int. Can't take a reference of a #define.
In C language const
object is not a constant. You cannot use it to declare a non-VLA array. Your first declaration is not compilable in C language, which makes it unclear what you mean by "functions fine".
See here for more details: Shall I prefer constants over defines?
In your case you are restricted to either #define
or enum
constants. If you also want to create pointers to that value, you will have to additionally declare a const
object with the same value, either globally or locally as needed. But you won't be able to use it in non-VLA array declarations. Instead, you will have to use the #define
or enum
constant. E.g.
// In .h file
#define BANANA_ARRAY_SIZE 10
extern const int BANANA_ARRAY_SIZE_OBJ;
// In .c file
const int BANANA_ARRAY_SIZE_OBJ = BANANA_ARRAY_SIZE;
You can either use a enum or a #define
enum {
BANANA_ARRAY_SIZE = 10
};
or
#define BANANA_ARRAY_SIZE 10
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With