Implementation of Pointers in C++
Basic Pointer Operations
Storing address in
a pointer
int x = 5;
int* p = &x;
Printing address
and value
cout <<
"Address of x: " << p << endl;
cout <<
"Value at p: " << *p << endl;
Pointer
Dereferencing
Dereference =
Access value at the stored address
int x = 20;
int* p = &x;
cout <<
*p; // prints 20
Changing value via
pointer:
*p = 100; // modifies x
cout <<
x; // prints 100
Pointers and
Arrays
Arrays and
pointers are closely related. Pointer store first element address of array.
int arr[3] = {10,
20, 30};
int* p = arr; // arr = &arr[0]
Access elements
through pointer:
cout <<
*p; // 10
cout <<
*(p+1); // 20
cout <<
*(p+2); // 30
Pointer arithmetic
works in multiples of data type size.
Pointer Arithmetic
|
Operation |
Meaning |
|
p++ |
Move to next
element |
|
p-- |
Move to previous
element |
|
p + n |
Move forward n
elements |
|
p - n |
Move backward n
elements |
Example:
int arr[] =
{2,4,6,8};
int* p = arr;
cout <<
*p; // 2
p++;
cout <<
*p; // 4
Pointers to
Pointers (Double Pointer)
A pointer storing
the address of another pointer.
int x = 10;
int* p = &x;
int** q = &p;
Access values:
cout <<
x; // 10
cout <<
*p; // 10
cout <<
**q; // 10
Pointers and
Functions
Pass-by-pointer
Used to modify
values inside a function.
void update(int*
p) {
*p = *p + 10;
}
int main() {
int x = 5;
update(&x);
cout << x; // 15
}
Dynamic Memory
Allocation
Allocate memory:
int* p = new
int; // allocate 4 bytes
*p = 10;
Allocate array:
int* arr = new
int[5];
Free memory:
delete p; // free 1 variable
delete[] arr; // free array
delete
Avoids memory
leaks.
Void Pointers
Can store address
of any data type, but cannot be directly dereferenced.
void* p;
int x = 10;
p = &x;
Must cast:
cout <<
*(int*)p;
Null Pointer
Pointer that
points to nothing.
int* p = nullptr;
Used for safety
checks.
Wild Pointer
Uninitialized
pointer (dangerous!).
int* p; // wild
Fix:
p = nullptr;
Dangling Pointer
Pointer pointing
to deleted or out-of-scope memory.
Example:
int* p = new
int(5);
delete p;
cout <<
*p; // DANGEROUS
Fix:
p = nullptr;
Complete Practical
Example
#include
<iostream>
using namespace
std;
int main() {
int x = 50;
int* p = &x;
cout << "Value of x: "
<< x << endl;
cout << "Address of x: "
<< &x << endl;
cout << "Pointer p stores:
" << p << endl;
cout << "Value at p: "
<< *p << endl;
*p = 200;
cout << "New value of x: "
<< x << endl;
int arr[3] = {1, 2, 3};
int* q = arr;
cout << *(q+0) << " "
<< *(q+1) << " " << *(q+2) << endl;
return 0;
}
0 Comments