Pointer in C++: A pointer, is basically a variable that stores the memory address or location as its value. It points to a data type (like int or string or char) of a similar type and is generated with the * operator. The address of the variable one is working with is assigned to the pointer:
For example –
string education = “techStudy”; // an education variable of type string
string* ptr = &education; // A pointer variable ptr, that stores the address of education
// Outputs the value of education (techStudy)
cout << education << “\n”;
// Outputs the memory address of education (0x6dfed4)
cout << &education << “\n”;
// Outputs the memory location of food with the pointer (0x6dfed4)
cout << ptr << “\n”;
Explanation – We created a pointer variable with the name ptr, that will point to a string variable. Keeping in my mind that the type of the pointer has to match the type of the variable we’re working with. We can use the & operator to store the memory location or address of the variable called education and assign it to the pointer. As a result, ptr will hold the value of the educations’ memory address.
Consider the following example:
- Write a C++ code to swap values of two variables using pointers.