Q&A: Pointers and memory

What is the address-of operator? How do we access the address of a variable?

string cat_name = "Kabe";
cout << "Address: " << &cat_name << endl; // Display address of this variable

How do we declare a pointer variable?

string *ptrCat = nullptr; // This is a pointer variable that stores string memory addresses.

How do we assign a pointer variable the address of another variable?

ptrCat = &cat_name; // Store the address of cat_name as the value of the ptrCat pointer variable.

When a pointer is not in use, what should it be pointing to?

What is the de-reference operator?

string cat1 = "Kabe";
string cat2 = "Luna";

string* ptrCat = &cat1; // Point ptrCat to the address of cat1.

cout << "ptrCat is pointing to address: " << ptrCat << endl;
cout << "Value at that address is:      " << *ptrCat << endl;
cout << "Enter a new value: ";
getline( cin, *ptrCat );

// Now cat1 will be whatever the user entered in.
cout << "Cats are now: " << cat1 << ", " << cat2 << endl;

Author: Rachel Wil Sha Singh

Created: 2023-10-27 Fri 15:49

Validate