0

Let`s say I have 2 structs:

struct Foo
{
    int size;  // 4
    int type;  // 4
    char data; // 1
};

static const struct Foo FooContainer[] = {
{1, 2, 3},
{4, 5, 6},
...
};

If I use something like:

int structsincontainer = sizeof(FooContainer) / sizeof(struct Foo);

Will I always get the correct number of structs in the container? I assume since the padding is already done in struct Foos the container will not need any padding?

CS_EE
  • 399
  • 2
  • 10
  • 1
    "Let`s say I have 2 structs:" You don't. You have 1 struct and an array of struct. Not a "struct containing struct". – Gerhardh Feb 01 '18 at 09:39

2 Answers2

4

FooContainer is an array. Arrays in both C and C++ are guaranteed to not add padding between their elements. Any padding that may be present is only that which is internal to the element object type itself.

So yes, the sizeof trick is a common technique that is guaranteed to work, so long as the parameter to sizeof is indeed the name of an array, and not a pointer that was obtained by an array-to-pointer conversion.

Having said all that, since you tagged C++, try to avoid raw arrays. The C++ standard library has several alternatives that provide greater safety and more functionality.

And even if you do use a raw array, a better way to obtain the size in C++ would be with the help of the type system itself:

template<typename T, std::size_t N>
constexpr auto array_size(T(&)[N]) { return N; }

The above is very easy to use like so int structsincontainer = array_size(FooContainer); and will only accept an array reference, instead of silently building when passed a pointer by accident.

StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458
1

That's correct. The padding is already considered in sizeof(struct foo).

In general, for any array T arr[n]; (where T is any type), sizeof arr == (n * sizeof(T)). This is guaranteed by the language.

aaaaaa123456789
  • 5,541
  • 1
  • 20
  • 33