1

Let's say, I have in a C application a structure:

typedef struct {
    int aParameter;
    int anotherParameter;
} Structure_t;

and an array of Structure_t elements:

const Structure_t arrayOfStructres[] = {
    {
        .aParameter = 1,
        .anotherParameter = 2
    },
    {
        .aParameter = 3,
        .anotherParameter = 4
    },
};

The arrayOfStructures is constant, so no changes during runtime. This means, that theoretically the number of elements in the array is known during compilation time. I know I could calculate the number of elements with

sizeof(arrayOfStructures) / sizeof(arrayOfStructes[0]);

during runtime, but how to get the number of elements during compilation time with the preprocessor? As the number of elements may be much more than just the two in the example, counting every element when some are added or removed is not very fast and also error prone.

3

3 Answers 3

2

I know I could calculate the number of elements with sizeof(arrayOfStructures)/sizeof(arrayOfStructes[0]); during runtime

No, that calculation is done at compile-time, so it is what you need.

The only calculation of sizeof that is done in run-time is the special case of VLAs, which doesn't apply here.

Sign up to request clarification or add additional context in comments.

Comments

2

The const qualifier has nothing to do with the number of elements in given array. The arrays in C are of fixed size (well, with notable exception to flexible array member, but it is diffrent thing), with no possibility of extending their elements at runtime.

The sizeof operator will (indirectly) give you the number of elements at compile-time. The only exception is with VLA (variable length) arrays, for which sizeof is calculated are runtime, but even with them, you cannot add more elements after declaration (because of that "variable length" is somewhat unfortunate name).

1 Comment

To be pedantic: sizeof returns number of bytes. sizeof(array)/sizeof(type_of_element) returns number of elements. ;)
0

I think you can use _countof Macro which operates at compile time, for more information take a look at here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.