Search⌘ K

Pointers and Arrays

Explore how pointers work with arrays in C by examining memory addresses, creating pointers to elements and arrays, and understanding types. Learn to differentiate between array names, element pointers, and whole array pointers to improve coding accuracy and memory management.

Introduction

Our goal is to validate the memory drawing we created before by writing code and checking the memory addresses.

This was the function we created:

func()
{
    int x;
    int arr[3];
}

The following is the drawing of the function:

Validating the memory drawing

We can write code to validate the memory drawing. Let’s declare the array and print the address of every element.

To do this, we can use the address-of operator (&) on any element inside the array (arr[i]).

C
#include <stdio.h>
int main()
{
int arr[3];
printf("Address of arr[0] = %u\n", &(arr[0]));
printf("Address of arr[1] = %u\n", &(arr[1]));
printf("Address of arr[2] = %u\n", &(arr[2]));
return 0;
}

We’re printing in base 10 again, so we can easily analyze the output. Note that the output may vary.

Address of arr[0] = 1411544388
Address of arr[1] = 1411544392
Address of arr[2] = 1411544396

We can see that:

  • arr[0] is the start of the array, with the address 1411544388.
  • The difference between arr[0] and arr[1] is 4 bytes, which is the size of arr[0].
  • The difference between arr[1] and arr[2] is 4 bytes, which is the size of arr[1].
  • arr[2] starts at address 1411544396, and since it is also 4 bytes (int), we can deduce it ends at
...