We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

Multibyte Arrays

If we create an array of structs it gets crazy because we can access and manipulate the elements using either indexing or pointer arithmetic. Let's see how multi-byte width structures are managed in memory.

First, let's say we're working with our familiar Coordinate struct:

typedef struct Coordinate {
  int x;
  int y;
  int z;
} coordinate_t;

We can declare an array of 3 Coordinate structs like so:

coordinate_t points[3] = {
  {1, 2, 3},
  {4, 5, 6},
  {7, 8, 9}
};

Then we can print out the values of the second element in the array:

printf("points[1].x = %d, points[1].y = %d, points[1].z = %d\n",
  points[1].x, points[1].y, points[1].z
);
// points[1].x = 4, points[1].y = 5, points[1].z = 6

Or we can use a pointer:

coordinate_t *ptr = points;
printf("ptr[1].x = %d, ptr[1].y = %d, ptr[1].z = %d\n",
  (ptr + 1)->x, (ptr + 1)->y, (ptr + 1)->z
);
// ptr[1].x = 4, ptr[1].y = 5, ptr[1].z = 6

Memory Layout

Assuming each int is 4 bytes, the Coordinate structure will be 12 bytes (3 * 4 bytes). Let's assume the points array starts at memory address 0x2000.

Here is the memory layout:

AddressElementValueOffset (bytes)
0x2000points[0].x10
0x2004points[0].y24
0x2008points[0].z38
0x200Cpoints[1].x412
0x2010points[1].y516
0x2014points[1].z620
0x2018points[2].x724
0x201Cpoints[2].y828
0x2020points[2].z932

Accessing Elements Using Pointers

  • points + 0 or &points[0] points to 0x2000

  • points + 1 or &points[1] points to 0x200C (next structure, offset by 12 bytes)

  • points + 2 or &points[2] points to 0x2018