PREV INDEX NEXT

Author: Stan Eisenstat
Subject: Re: [Cs223] Alignment on Structs
Date: Thursday, 09 Apr 2020, 10:48:32


    > Message Posted By: Unknown
    >
    > Is memory for structs automatically set to multiples of 8 bytes when
    > storing them dynamically? Currently, I have a struct which contains a
    > pointer (8 bytes) to another struct and an int (4 bytes), and when I
    > dynamically allocate memory for this struct it allocates 16 bytes. My
    > computer and the zoo are both 32-bit so I thought that they have
    > processing sizes of 4 bytes, so I am not entirely sure.

sizeof(struct name) is always a multiple of the widest
field.  For example:

  struct {char a;}                      1
  struct {char a; char b;}              2
  struct {char a; char b; char c;}      3
  struct {int a;}                       4
  struct {int a; char b;}               8
  struct {int a; char b; int c;}       12
  struct {long a; char b;}             16

This ensures that if you create an array of structs, all
of the fields in all of the elements will be aligned.

Nice question.

--Stan-
PREV INDEX NEXT