0

I have been asked to replace arrays in a C struct by C++ std::array. The C struct is a packed struct that directly translates into memory from an input buffer. Something like:

struct [[gnu::packed]] s {
    int a;
    int b[5];
    int c;
};

struct s s1;

So that struct was being filled with a simple call to memcpy:

std::memcpy(s1, buff, sizeof(s1));

Now I should have something like:

struct [[gnu::packed]] sxx {
    int a;
    std::array<int, 5> b;
    int c;
}

However, I'm concerned that the std::array may be having some secret stuff in the end of it (to keep info about its size, for example), and that it may break the ability to fill struct sxx with the same simple std::memcpy() call.

Can std::arrays transparently replace C arrays in packed structs, or do I need to assign elements separately to avoid memory layout issues?

  • 1
    `std::array` has no "extra stuff". The size is part of the type. – 463035818_is_not_an_ai Jul 05 '21 at 14:55
  • The linked question seems to imply that the standard doesn't guarantee that there's no "extra stuff". It just states that current implementations seem to not have "extra stuff". That's more or less what I had found prior to asking. Is there any guarantee that it is safe to use in packed structs? Does `[[gnu::packed]]` affect it? – alx - recommends codidact Jul 05 '21 at 14:58
  • 1
    I didnt read the standard, but cppref suggests that there must not be any extra stuff ["This container is an aggregate type with the same semantics as a struct holding a C-style array `T[N]`as its only non-static data member."](https://en.cppreference.com/w/cpp/container/array) – 463035818_is_not_an_ai Jul 05 '21 at 15:00
  • 1
    You can test `static_assert(sizeof(std::array) == sizeof(int[5]));` and test both sizeof(s). – 273K Jul 05 '21 at 15:01

0 Answers0