Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does a C struct hold its members in a contiguous block of memory? [duplicate]

Tags:

c

Let's say my code is:

typedef stuct {
  int x;
  double y;
  char z;
} Foo;

would x, y, and z, be right next to each other in memory? Could pointer arithmetic 'iterate' over them? My C is rusty so I can not quite get the program right to test this. Here is my code in full.

#include <stdlib.h>
#include <stdio.h>

typedef struct {
  int x;
  double y;
  char z;
} Foo;


int main() {
  Foo *f = malloc(sizeof(Foo));
  f->x = 10;
  f->y = 30.0;
  f->z = 'c';
  // Pointer to iterate.
  for(int i = 0; i == sizeof(Foo); i++) {
    if (i == 0) {
      printf(*(f + i));
    }
    else if (i == (sizeof(int) + 1)) {
      printf(*(f + i));
    }
    else if (i ==(sizeof(int) + sizeof(double) + 1)) {
      printf(*(f + i));
    }
    else {
      continue;
    }
  return 0;
}
like image 214
David Frick Avatar asked Nov 27 '22 19:11

David Frick


1 Answers

No, it is not guaranteed for struct members to be contiguous in memory.

From §6.7.2.1 point 15 in the C standard (page 115 here):

There may be unnamed padding within a structure object, but not at its beginning.

Most of the times, something like:

struct mystruct {
    int a;
    char b;
    int c;
};

Is indeed aligned to sizeof(int), like this:

 0  1  2  3  4  5  6  7  8  9  10 11
[a         ][b][padding][c          ]
like image 65
Marco Bonelli Avatar answered Dec 17 '22 00:12

Marco Bonelli