pointer
🧩 1️⃣ Basic Pointer
👉 A pointer stores the address of another variable.
#include <iostream>
using namespace std;
int main() {
int a = 10;
int *p = &a;
cout << "Value of a: " << a << endl;
cout << "Address of a: " << &a << endl;
cout << "Pointer p: " << p << endl;
cout << "Value pointed by p: " << *p << endl;
}
✅ Key Points:
&a→ gives address ofa*p→ gives value stored at that addressHelps in dynamic memory and function parameter passing
🧮 2️⃣ Pointer to Pointer
👉 Stores the address of another pointer.
#include <iostream>
using namespace std;
int main() {
int x = 100;
int *p = &x;
int **q = &p;
cout << "x = " << x << endl;
cout << "*p = " << *p << endl;
cout << "**q = " << **q << endl;
}
🧠 Memory Chain:
x = 100
p → address of x
q → address of p
✅ Use: Multi-level data like 2D arrays, dynamic structures (linked lists, trees).
📦 3️⃣ Pointer with Arrays
👉 Array name acts like a pointer to its first element.
#include <iostream>
using namespace std;
int main() {
int arr[3] = {10, 20, 30};
int *p = arr; // same as &arr[0]
cout << *p << endl; // 10
cout << *(p + 1) << endl; // 20
cout << *(p + 2) << endl; // 30
}
✅ Key Points:
arr[i]is same as*(arr + i)Useful for pointer arithmetic and array traversal
🔄 4️⃣ Pointer with Functions (Call by Reference)
👉 Lets you modify variable values inside functions directly.
#include <iostream>
using namespace std;
void swap(int *x, int *y) {
int temp = *x;
*x = *y;
*y = temp;
}
int main() {
int a = 5, b = 10;
swap(&a, &b);
cout << "After swap: a = " << a << ", b = " << b << endl;
}
✅ Use:
Pass variables by address
Saves memory and improves performance
⚙️ 5️⃣ Null Pointer
👉 A pointer that points to nothing (address = 0).
#include <iostream>
using namespace std;
int main() {
int *p = NULL; // or nullptr (C++11)
if (p == NULL)
cout << "Pointer is null!" << endl;
}
✅ Use:
Initialize pointers safely
Prevent crashes due to wild pointers
☠️ 6️⃣ Dangling Pointer
👉 A dangling pointer points to memory that has been freed or deleted —
but the pointer still holds that old address.
Example 1: Returning local variable’s address
#include <iostream>
using namespace std;
int* fun() {
int a = 10;
return &a; // ❌ 'a' will be destroyed after function ends
}
int main() {
int *p = fun();
cout << *p << endl; // ❌ invalid, dangling pointer
}
Example 2: Deleting memory
#include <iostream>
using namespace std;
int main() {
int *p = new int(5);
delete p; // memory released
// p still holds the old address (dangling)
cout << *p << endl; // ❌ undefined behavior
p = NULL; // ✅ fix it
}
✅ Fix:
Set pointer to
NULLafter deleting memoryAvoid returning addresses of local variables