C++ Pointer
In C++, a pointer is a variable that stores the memory address of another variable. Pointers are an important concept in C++, as they allow us to manipulate memory directly and create complex data structures.
To declare a pointer variable in C++, we use the asterisk *
operator. For example, to declare a pointer to an integer, we would write:
int* ptr;
This declares a pointer variable named ptr
that can hold the memory address of an integer.
We can assign a memory address to a pointer variable using the address-of operator &
. For example, to assign the address of an integer variable named num
to our ptr
pointer, we would write:
int num = 42; int* ptr = #
This sets the value of ptr
to the memory address of num
.
We can also dereference a pointer using the asterisk *
operator. This allows us to access the value stored at the memory address pointed to by the pointer. For example, to access the value of the integer variable that our ptr
pointer points to, we would write:
int num = 42; int* ptr = # std::cout << *ptr << std::endl; // Output: 42
This outputs the value of num
, which is 42.
Pointers can also be used to create dynamic data structures like linked lists and trees. In these cases, we allocate memory dynamically using the new
keyword, which returns a pointer to the newly allocated memory. We can then use these pointers to construct our data structures. It's important to manage memory properly when using pointers to avoid memory leaks and other issues.