Pointers
Declaration and Initialization:
// Declaration of a pointer
int* ptr;
// Initialization of a pointer with the address of a variable
int x = 10;
int* ptr = &x;
In the above example, int*
is the pointer type, and ptr
is a pointer variable that stores the address of an integer variable (x
in this case).
Accessing Value through Pointers:
int x = 10;
int* ptr = &x;
// Accessing the value through the pointer
int value = *ptr;
std::cout << "Value: " << value << std::endl;
The *
operator is used to dereference the pointer, i.e., obtain the value stored at the memory address it points to.
Pointer Arithmetic:
int numbers[] = {1, 2, 3, 4, 5};
int* ptr = numbers;
// Accessing array elements using pointer arithmetic
std::cout << "First element: " << *ptr << std::endl; // prints 1
// Moving to the next element
ptr++;
std::cout << "Second element: " << *ptr << std::endl; // prints 2
Pointer arithmetic allows you to navigate through memory addresses, making it useful when working with arrays or dynamic memory.
Null Pointers:
int* ptr = nullptr; // C++11 and later
// or
int* ptr = NULL; // pre-C++11
A null pointer doesn't point to any memory location. It is often used to indicate that the pointer is not currently pointing to a valid object.
Dynamic Memory Allocation (new and delete):
// Dynamic memory allocation
int* ptr = new int; // allocate memory for an integer
// Assigning a value to the dynamically allocated memory
*ptr = 42;
// Deallocating the memory
delete ptr;
Pointers and Functions:
void modifyValue(int* ptr) {
*ptr = 20;
}
int main() {
int x = 10;
int* ptr = &x;
modifyValue(ptr);
std::cout << "Modified value: " << x << std::endl; // prints 20
return 0;
}
These are basic concepts, and pointers have many other aspects and use cases, such as pointers to functions, pointer arrays, and more. Proper understanding and careful usage of pointers are essential for writing efficient and error-free C++ code.