0

As I know, strucutre elements are stored in continuous memory locations. To confirm the same, I written below sample application.

#include <stdio.h>

struct Employee{
    char firstName;
    float salary;
    int id;
};


int main(){

    struct Employee emp = {'K', 123456.78, 1};

    printf("firstName stored at location : %lu\n", &emp.firstName);
    printf("salary stored at location : %lu\n", &emp.salary);
    printf("id stored at location : %lu\n", &emp.id);

    return 0;
}

When I ran the application, I seen below kind of output.

firstName stored at location : 140732780083504
salary stored at location : 140732780083508
id stored at location : 140732780083512

As you see the output, firstName stored at location 140732780083504, and salary stored at location 140732780083508, can't the salary be at 140732780083505? Is the behavior like it always return end location of specific variable.

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Hari Krishna
  • 3,658
  • 1
  • 36
  • 57

2 Answers2

2

This is probably due to padding bytes. It is somewhat true that structs are, as you say, stored in continuous memory locations, however, compilers are free to add padding bytes inbetween elements however they choose and they do it in order to align fields to the architectures natural alignment. Words consisting of multiple bytes can usually only be accessed by a single instruction if they're naturally aligned.

Gamification
  • 787
  • 5
  • 20
  • This answer could be greatly improved by including information on *why* padding is used, – Angew is no longer proud of SO Jan 21 '19 at 09:28
  • Indeed, I tried to get it to the point, however I'm not sure if there aren't more reasons for padding… – Gamification Jan 21 '19 at 09:34
  • Padding is not required and C standard does not imposes/forbid padding. Among other reasons, it is a mean to insure that data addresses are aligned in such a way that no data is spread among two cache lines in order to speed up memory accesses. Compilers generally have a mean to control data alignment in structs – Alain Merigot Jan 21 '19 at 09:37
  • @AlainMerigot isnt that pretty much what I wrote? "compilers are free to add padding bytes inbetween elements however they choose" – Gamification Jan 21 '19 at 10:26
1

It happens because your compiler's default structure padding is 4 bytes. If you want your structure elements to follow one by one in memory use #pragma pack(push, 1)

Also this post can be useful to understand structure paddings: Structure padding and packing

Denis Sablukov
  • 3,360
  • 2
  • 26
  • 31