Pointers


    

Table of Contents

  1. Memory Address
  2. Pointers

Memory Address

Every variable that is created has its own memory address. A memory address is the location where a variable is stored on the computer. When we assign a value to the variable, it is stored in this memory address. To access the memory address of a variable, we can use the operator &. In C, a variable that stores the memory address of a variable is called a pointer and the format specifier for a pointer is %p.

Syntax: printf("%p", &variable_name)

Example:

#include<stdio.h> int main() { int myNum = 16; printf("%p", &myNum); return 0; }

Output:


    0x7ffc89b6e084
        

The memory address is represented in hexadecimal form and the variable's memory address may differ from a computer to another, so when you run this code on your computer, it's likely to have a different result from the one in the output example.

Pointers

As explained in the memory address section, a variable that stores the memory address of a variable is called a pointer and the format specifier for a pointer is %p. Defining a pointer variable is the same as defining other variables, except you have to write * after the variable type and before the variable name. The variable type of the pointer has to be the same as the variable type of the variable that the pointer points to.

Syntax:

variable_type variable_name1; variable_type* pointer_name1 = &variable_name1;

You can also print the variable that the pointer points by dereferencing by using * before the variable name in the printf statement. If we don't use *, then the compiler will print the memory address of the variable.

Syntax:

variable_type variable_name1; variable_type* pointer_name1 = &variable_name1; printf("%p", pointer_name1); //print the memory address of variable_name1 printf("format specifier of variable_name1", *pointer_name1); //print variable_name1

Example:

#include<stdio.h> int main() { //variable declaration char myChar = 'C'; int myAge = 18; //pointer declaration char* myptr1 = &myChar; int* myptr2 = &myAge; printf("%p\n", myptr1); //print memory address of myChar printf("%c\n", *myptr1); //dereferencing (print myChar) printf("%p\n", myptr2); //print memory address of myAge printf("%d", *myptr2); //dereferencing (print myAge) return 0; }

Output:


    0x7ffdb8071ed3
    C
    0x7ffdb8071ed4
    18
        


    

In C, the name of an array is actually a pointer to the first element of the array. In other words, when we print array_name as a pointer by the format specifier %p is actually the same value as printing &array_name[0]. Therefore, we can access the elements in an array by dereferencing.

Example:

#include<stdio.h> int main() { int myNumbers[4] = {25, 50, 75, 100}; // Change the value of the second element to 23 *(myNumbers + 1) = 23; printf("%d ", *myNumbers); //print myNumbers[0] printf("%d", *(myNumbers + 1)); //print myNumbers[1] return 0; }

Output:


    25 23