C++ Pointers: Key Uses and Examples
C++ pointers are used to store the memory address of another variable. With pointers, you can directly access the value of the variable they point to, or modify that value. Here are some common uses of C++ pointers:
- Variable address: You can use a pointer to retrieve the address of a variable. For example, int* p = & num will store the address of an integer variable num in the pointer p.
- Dereferencing pointers: You can use the dereference operator (*) to access the value pointed to by a pointer, for example: int value = *p; assigns the value of the integer variable pointed to by pointer p to variable value.
- Dynamic memory allocation: using the new keyword to create dynamic memory and return the address of the allocated memory to a pointer, for example: int* p = new int; will allocate memory for an integer variable on the heap and store its address in the pointer p.
- Accessing arrays: You can use pointers to access the elements of an array, for example: int arr[] = {1, 2, 3}; int* p = arr; You can access the elements of the array arr using the pointer p.
- Function Pointer: Using pointers to store the address of a function allows for indirect invocation of the function. For example, int (*p)(int, int) = add; defines a pointer p to the function add, which can be used to call the add function.
- Arithmetic operations on pointers: Pointers can be subject to addition, subtraction, and other arithmetic operations. For example, p++ will increment the value of pointer p, causing it to point to the next element.
- Null pointer and null pointer constant: In C++, a null pointer is used to represent a pointer that does not point to any valid address, and nullptr keyword can be used to define a null pointer, for example: int* p = nullptr;
In general, the usage of C++ pointers is very flexible and can be applied in various scenarios such as dynamic memory allocation, array access, and function pointers. However, caution must be exercised when using pointers as they can easily lead to errors such as null pointer references or dangling pointers.