In C++ a Pointer
is a variable that holds the memory address of another variable. So instead of storing data directly, it stores the memory location of where to find the data.
In C++, pointers and references are commonly used frequently in software development, however they are not the same thing and there are differences between the two:
Feature | Pointer | Reference |
---|---|---|
Must be initialized? | No | Yes |
Can be reassigned? | Yes | No |
Can be null? | Yes | No |
Syntax | More flexible | More readable |
Used in dynamic memory | Yes | N/A |
Operation | Syntax | Meaning |
---|---|---|
Get address | &x | Where x lives in memory |
Declare pointer | int* ptr | ptr will point to an int |
Assign address | ptr = &x | ptr now knows where x is |
Dereference | *ptr | Gets or sets the value at ptr |
Null pointer | int* ptr = nullptr | Pointer points to nothing (safe default) |
int x = 42 ;
int * ptr = &x; // 'ptr' now stores the memory address of 'x'
// Output the value of x : 42
cout << x << "\n" ;
// Output the memory address of x : 0x6egfc9
cout << &x << "\n" ;
// Output the memory address of x with the pointer : 0x6egfc9
cout << ptr << "\n" ;
Let's break down int* ptr = &x;
:
int*
defines a pointer to an int
ptr
is the custom name of our pointer variable&x
gives the memory address of x
Thank you for reading, I hope you found this blog post (tutorial) educational and helpful.
About | Contact Us | Privacy | Terms & Conditions | © 2025 - T&J Divisions, LLC, All Rights Reserved |