C++ Pointers

πŸ‘‰ C++ Pointers

A pointer in C++ is a variable that stores the memory address of another variable.
Pointers are essential for dynamic memory, arrays, functions, and low-level programming.


πŸ”Ή 1. Pointer Declaration

int *ptr;
  • int β†’ type of data it points to

  • * β†’ pointer symbol

  • ptr β†’ pointer variable


πŸ”Ή 2. Pointer Initialization

int x = 10;
int *ptr = &x;
  • &x β†’ address of x

  • ptr stores that address


πŸ”Ή 3. Access Value Using Pointer (Dereferencing)

cout << *ptr; // Output: 10
  • ptr β†’ address

  • *ptr β†’ value at that address


πŸ”Ή 4. Change Value Using Pointer

*ptr = 25;
cout << x; // Output: 25

πŸ”Ή 5. Pointer and Array Relationship

int arr[3] = {10, 20, 30};
int *p = arr;

cout << *p; // 10
cout << *(p + 1); // 20
cout << *(p + 2); // 30


πŸ”Ή 6. Pointer Arithmetic

p++; // moves to next element

➑ Pointer moves by sizeof(type) bytes.


πŸ”Ή 7. Null Pointer

int *p = nullptr;

βœ” Safe initialization
βœ” Avoids garbage address


πŸ”Ή 8. Pointer in Functions (Call by Reference)

void change(int *x) {
*x = 50;
}

int a = 10;
change(&a);
cout << a; // 50


πŸ”Ή 9. Pointer vs Reference

PointerReference
Can be NULLCannot be NULL
Can be reassignedCannot be reassigned
Needs dereferencingNo dereferencing
More flexibleSafer & simpler

πŸ”Ή 10. Common Pointer Types

Pointer to Pointer

int x = 10;
int *p = &x;
int **pp = &p;

Constant Pointer

int x = 10;
int *const p = &x;

Pointer to Constant

const int x = 10;
const int *p = &x;

❌ Common Mistakes

int *p;
*p = 10; // ❌ uninitialized pointer

βœ” Correct:

int x = 10;
int *p = &x;

πŸ“Œ Summary

  • Pointer stores a memory address

  • & β†’ get address, * β†’ access value

  • Used with arrays, functions, dynamic memory

  • Must be initialized properly

You may also like...