C++ Pointers

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Introduction

A pointer is an address that refers to a location in memory. They're commonly used to allow functions or data structures to know of and modify memory without having to copy the memory referred to. Pointers are usable with both primitive (built-in) or user-defined types.

Pointers make use of the "dereference" * , "address of" & , and "arrow" -> operators. The '*' and '->' operators are used to access the memory being pointed at, and the & operator is used to get an address in memory.

Syntax

  • <Data type> *<Variable name>;
  • <Data type> *<Variable name> = &<Variable name of same Data type>;
  • <Data type> *<Variable name> = <Value of same Data type>;
  • int *foo; //A pointer which would points to an integer value
  • int *bar = &myIntVar;
  • long *bar[2];
  • long *bar[] = {&myLongVar1, &myLongVar2}; //Equals to: long *bar[2]

Remarks

Be aware of problems when declaring multiple pointers on the same line.

int* a, b, c; //Only a is a pointer, the others are regular ints.

int* a, *b, *c; //These are three pointers!

int *foo[2]; //Both *foo[0] and *foo[1] are pointers.


Got any C++ Question?