0

How is a struct in C sized? For example with the below:

struct Person {
    char* name;
    char age;
};

int main(int argc, char* argv[]) {
    struct Person person1;
    person1.name = "John Smith";
    person1.age = 40;
    printf("The size of the Person object is: %lu.\n", sizeof(person1));
}

This gives me a size of 16 and not 9. How is a struct aligned then or is it dependent on the architecture or C implementation? For example, is it on 16-byte boundaries, 8-byte boundaries, etc.?

samuelbrody1249
  • 4,379
  • 1
  • 15
  • 58

1 Answers1

0

It's architecture dependent. But you usually can control the size or alignment through attributes. If you packed the structure via a pragma, you could make the size 9 bytes (assuming an 8 byte pointer).

See C struct size alignment

Boxtor
  • 1
  • But you run the risk of dramatically impacting the efficiency. Iterating over a block of memory on 9-byte boundaries will be much slower than 16-byte boundaries. – David C. Rankin Nov 01 '20 at 02:27
  • This is definitely true. I mentioned how to get the specific sizes. There can also be problems with unaligned data access on certain architectures. Packing a structure is very usage dependent. – Boxtor Nov 01 '20 at 03:26