/ coding

Understanding Pointers in C

About pointers

In C, you have pretty close control over the hardware you are programming. When you store a variable, you can actually know the address of that set of bytes in memory. A pointer is a variable that contains the address (in memory) of another variable. Why would you want to use this? If you are programming in C, you are either living in the 80s, or programming a microcontroller. C gives you control over the memory performance, which is not as big of an issue with the computer hardware we have today. However, MCUs are small and often don't have much memory, so knowing the exact location of a value can help you reference the same exact data without making unecessary copies. It is also required in C to use arrays, strings, and writeable function parameters. For a straight to the point article on why C has pointers, and when to use them, see Why C has Pointers. This article will explain how to use them.

Syntax

There are two symbols used when dealing with pointers:

  • &
  • *

These symbols, when used in front of a variable mean the following:

myPointer = &myVariable;    // myPointer contains the address of the value referenced by myVariable
myVariable2 = *myPointer;   // myVariable2 contains the value (at the address) stored in myPointer

Consider this code:

#include <stdio.h>

int main()
{
    int myVariable = 1;
    int *myPointer = &myVariable;   // myPointer contains the address of the value referenced by myVariable
    int myVariable2 = *myPointer;   // myVariable2 contains the value (at the address) stored in myPointer
    printf("myVariable: %d\n", myVariable);
    printf("myPointer: %d\n", myPointer);
    printf("myVariable2: %d\n", myVariable2);
}

When compiled and run,

$ ./test.exe
myVariable: 1
myPointer: 2271936
myVariable2: 1