Pointers


Pointers are one of the essential programming features which are available in C.

Pointers are heavily used in embedded C programming to:

A pointer points to a memory address where a variable is stored


The address of a variable is the physical location of a variable in memory. It can be accessed with the & keyword.

Having the address of a variable can be useful so the location in memory of a variable can be accessed by a pointer later on.

VariableAddress.png

#include <stdio.h>

int main(){
	int variable1 = 23;   // Declate an integer variable
	int* ptr;       // Declare a pointer to an integer
	ptr = &var;     // Assing the pointer the address of the variable

    cout << "Value of variable1: " << variable1 << endl;
    cout << "Address of varariable1: " << &variable1 << endl;
    cout << "Value of ptr (Address it holds): " << ptr
         << endl;
    cout << "Value pointed to by ptr: " << *ptr
         << endl; // Dereferencing pointer to access the
                  // value of var

    return 0; 
}

[1]
where the output is as follows:

Value of var: 23
Address of var: 0x00007FFF8E1
Value of ptr (Address it holds): 0x00007FFF8E1
Value pointed to by ptr: 23

How to store a pointer inside a program?

Syntax

<pointer data type> <variable name>

Pointer data types

Data type Data type
char* unsigned char*
int* unsigned int*
long long int* unsigned long long int*`
float* unisgned float*
double* unsigned double*

Creating a pointer in a script

If we want to assign a specific address to a pointer, we might be tempted to do something like this:

char* address1 = 0x00007FFF8E3C3824

But this won't work because for the compiler, this is a simple number and NOT an address.

To correctly assign an address to a pointer, we shall type cast the address like this:

char* address1 = (char*) 0x00007FFF8E3C3824

where:

Note that the compiler will always reserve 8 bytes for the pointer variable irrespective of their data type. In other words, the pointer data type doesn't control the memory size of the pointer variable.

So, all of these pointers will be stored in 8 bytes of data:

char* address1;          // 8 bytes stored for the address
int* address2;           // 8 bytes stored for the address
long long int* address3; // 8 bytes stored for the address
double* address1;        // 8 bytes stored for the address

  1. Types of Pointer in Programming - GeeksforGeeks ↩︎