Lesson 3 of 46
Lesson Progress: 0%
Pointers store memory addresses and allow direct access to data in memory. They are a fundamental C++ feature that gives you low-level control over how data is stored and manipulated. Pointers support arithmetic, can be null, and can be reassigned to point to different objects. They are the backbone of dynamic memory allocation, data structures like linked lists, and array processing. This lesson covers declaring pointers, dereferencing, null checks, pointer arithmetic, and using pointers as parameters. Mastering pointers is essential for understanding how C++ manages memory at a granular level.
#include <iostream>
using namespace std;
int main() {
int x = 42;
int* ptr = &x;
cout << *ptr;
return 0;
}Instructions
▼ ← Click the triangle to hide or reveal instructions.Task Incomplete
Editor Input:
Editor Output:
int* ptr = &x declares a pointer and stores the address of x.& operator returns the memory address of a variable.* operator dereferences the pointer to access the value at that address.cout << *ptr prints the value stored at the address held by ptr.#include <iostream>
using namespace std;
int main() {
int x = 10;
int* ptr = &x;
*ptr = 77;
cout << x;
return 0;
}Instructions
▼ ← Click the triangle to hide or reveal instructions.Task Incomplete
Editor Input:
Editor Output:
*ptr = 77 writes 77 into the memory location that ptr points to.x directly because ptr holds x address.#include <iostream>
using namespace std;
int main() {
int* ptr = nullptr;
if (ptr == nullptr) {
cout << "null";
} else {
cout << *ptr;
}
return 0;
}Instructions
▼ ← Click the triangle to hide or reveal instructions.Task Incomplete
Editor Input:
Editor Output:
nullptr pointer points to nothing and should not be dereferenced.nullptr before using a pointer to avoid crashes.ptr == nullptr checks whether the pointer is safe to use.nullptr over the older NULL macro.#include <iostream>
using namespace std;
int main() {
int arr[] = {10, 20, 30};
int* ptr = arr;
cout << *ptr << " ";
ptr++;
cout << *ptr;
return 0;
}Instructions
▼ ← Click the triangle to hide or reveal instructions.Task Incomplete
Editor Input:
Editor Output:
ptr++ moves to the next element.arr decays to a pointer to its first element.#include <iostream>
using namespace std;
void increment(int* p) {
(*p)++;
}
int main() {
int x = 5;
increment(&x);
cout << x;
return 0;
}Instructions
▼ ← Click the triangle to hide or reveal instructions.Task Incomplete
Editor Input:
Editor Output:
&x, and the function receives it as int* p.(*p)++ increments the value at the pointed-to address.*p++ would increment the pointer, not the value.#include <iostream>
using namespace std;
int main() {
int x = 42;
int* ptr = &x;
int** pptr = &ptr;
cout << **pptr;
return 0;
}Instructions
▼ ← Click the triangle to hide or reveal instructions.Task Incomplete
Editor Input:
Editor Output:
int** pptr = &ptr.**pptr.Test Incomplete