34) Pointers Part 2¶
cout << &a, then you get the Memory Address where a is stored. So whenever, for some reason, you need to know the Address, you do that. But with an int, there’s 4 bytes. Four Memory Locations, so Four Memory Addresses. Meaning &a is actually referring to the first of those 4 addresses. To explain in House terms, you needed more than one house, so you decided to buy 4 of them side by side, and use them all at once. You build one gigantic house on that. Although there’s still 4 addresses, it’s all just one house. And if anyone asks for the address, then you give the address to the start. The output of &a will be different for different computers and environments, but the concept is still the same.int*. That first word instead serves the programmer. (Stuff)* means, I’m declaring a Pointer which will Point specifically to Stuff. And Stuff can be anything. An Int, Float, Char, String, and later in Semester 2 when we do OOP, it can also be custom data types. It can even be another pointer, but that comes way later.1 2 3 4 5 6 7 8 9 10 11 | |
ptr because it’s easy to identify. The declarations of ptr1, ptr2, and ptr3 are all correct. But the declarations of ptr4, ptr5, and ptr6 aren’t. The reason? The data types the pointers are declared with don’t match up with the data types of the actual variables they’re pointing to. It’s important for them to match, specifically for two reasons:So the programmer knows what kind of Data the pointer is pointing to. Makes programming easier. You don’t accidentally mix things up because the program forbids you to.
The more important reason is Pointer Arithmetic. We’ll get to that in a bit.
1 2 3 4 5 6 7 8 | |
a through p? Well, remember how the * symbol has multiple uses? It’s used here once again, for dereferencing.1 2 3 4 5 6 7 8 | |
ptrA and ptrB hold the memory addresses of a and b respectively. So if we want to see the actual values at the addresses of ptrA and ptrB, we just Dereference them, by doing *ptrA. This operation is the same as saying “the value at this location”. So you can use them like regular variables as well.1 2 3 4 5 6 7 8 9 10 11 | |
1 2 3 | |
int a = 0; or int a[5] = {};.1 | |
Pointers are
intdata types that hold Memory AddressesThey’re important for Memory Control and Dynamic Memory
The pointer’s data type has to match the variable’s data type so Pointer Arithmetic can be done properly
Changing the value of a variable will not store the address of it, and hence, won’t affect the Pointer
Pointers can be dereferenced for accessing the values stored at their addresses
Multiple Pointers can point to a single Memory Address
Declare a pointer as NULL if there immediately isn’t a Memory Location to assign to it