C++ Pointers

Working with pointers and memory addresses

Pointer Declaration

int* ptr; # declare int pointer
double* dPtr; # declare double pointer
char* cPtr = nullptr; # initialize to null

Address and Dereference

int num = 10; # create variable
int* ptr = # # store address of num
cout << ptr; # print memory address
cout << *ptr; # print value (10)
*ptr = 20; # modify value through pointer

Dynamic Memory

int* ptr = new int; # allocate single int
*ptr = 42; # assign value
delete ptr; # free memory
int* arr = new int[5]; # allocate array
arr[0] = 10; # access element
delete[] arr; # free array memory

References

int num = 5; # original variable
int& ref = num; # create reference (alias)
ref = 10; # modifies num to 10
cout << num; # prints 10

Pointer Arithmetic

int arr[] = {10, 20, 30}; # array
int* ptr = arr; # points to first element
ptr++; # move to next element
cout << *ptr; # prints 20