C++ Pointers
In C++, a pointer is a variable that stores the memory address of another variable. Pointers are used for dynamic memory allocation, accessing array elements, and building data structures like linked lists and trees.
1. Declaring and Using Pointers
Example of declaring and using pointers:
#include <iostream>
int main() {
// Declare a variable and a pointer
int num = 10;
int *ptr;
// Assign the address of num to ptr
ptr = #
// Output the value of num and ptr (memory address)
std::cout << "num = " << num << std::endl;
std::cout << "ptr = " << ptr << std::endl;
// Access the value of num through ptr
std::cout << "Value of num through ptr = " << *ptr << std::endl;
return 0;
}
2. Dynamic Memory Allocation
Example of dynamic memory allocation using pointers:
#include <iostream>
int main() {
// Declare a pointer to an integer
int *ptr;
// Allocate memory dynamically for an integer
ptr = new int;
// Assign a value to the allocated memory
*ptr = 25;
// Output the value
std::cout << "Value at ptr: " << *ptr << std::endl;
// Deallocate the memory
delete ptr;
return 0;
}
3. Pointers and Arrays
Example of using pointers with arrays:
#include <iostream>
int main() {
int numbers[5] = {1, 2, 3, 4, 5};
int *ptr;
// Assign the address of the first element of the array to ptr
ptr = numbers;
// Output elements of the array using pointer arithmetic
for (int i = 0; i < 5; ++i) {
std::cout << "Element " << i << ": " << *(ptr + i) << std::endl;
}
return 0;
}
Conclusion
Pointers in C++ provide powerful capabilities for manipulating memory addresses, enabling dynamic memory allocation and efficient access to data structures. This chapter covered basic pointer declaration, dynamic memory allocation with pointers, using pointers with arrays, and pointer arithmetic. Understanding pointers allows you to manage memory resources and implement complex data structures in your C++ programs.