Samual Phillips
Samual Phillips

Reputation: 61

How can I find the size of a const declared array in C?

In file1.c, I have the array

const uint8 myArray[] =
{
    0x4b, 0x28, 0x05, 0xbf,   
    ...
    0xff, 0xff, 0xff, 0xff
};

In file2.c, I need to use the array as follows:

uint8* buffer = myArray;
uint32 length = ???

I've tried length = sizeof(myArray), but this results in the following error:
error: invalid application of ‘sizeof’ to incomplete type ‘const uint8[] {aka const unsigned char[]}’. Since it is constant, I could physically count the number of entries, but I need to do it programmatically because this constant is likely to change further on in development.

Upvotes: 4

Views: 120

Answers (1)

Acorn
Acorn

Reputation: 26066

In file1.c, export the length:

const size_t myArrayLength = sizeof(myArray);

And then add a declaration somewhere (in a header file for file1.c or maybe directly in file2.c) like:

extern const size_t myArrayLength;

Upvotes: 4

Related Questions