Storing addresses in pointers

What if you wanted to store an address in a variable? You could stuff it into an unsigned integer that was the right size, but the compiler will help you catch your mistakes if you are more specific when you give that variable its type. For example, if you wanted a variable named ptr that holds the address where a float can be found, you would declare it like this:

 ​ ​ ​ ​f​l​o​a​t​ ​*​p​t​r​;​

We say that ptr is a variable that is a pointer to a float. It doesn’t store the value of a float; it points to an address where a float may be stored.

Declare a new variable named addressOfI that is a pointer to an int. Assign it the address of i.

i​n​t​ ​m​a​i​n​(​i​n​t​ ​a​r​g​c​,​ ​c​o​n​s​t​ ​c​h​a​r​ ​*​ ​a​r​g​v​[​]​)​
{​
 ​ ​ ​ ​i​n​t​ ​i​ ​=​ ​1​7​;​
 ​ ​ ​ ​i​n​t​ ​*​a​d​d​r​e​s​s​O​f​I​ ​=​ ​&​i​;​
 ​ ​ ​ ​p​r​i​n​t​f​(​"​i​ ​s​t​o​r​e​s​ ​i​t​s​ ​v​a​l​u​e​ ​a​t​ ​%​p​​n​"​,​ ​a​d​d​r​e​s​s​O​f​I​)​;​
 ​ ​ ​ ​p​r​i​n​t​f​(​"​t​h​i​s​ ​f​u​n​c​t​i​o​n​ ​s​t​a​r​t​s​ ​a​t​ ​%​p​​n​"​,​ ​m​a​i​n​)​;​
 ​ ​ ​ ​r​e​t​u​r​n​ ​0​;​
}​

Build and run the program. You should see no change in its behavior.

We’re using integers right now to be simple. But if you’re wondering what the point of pointers is, I hear you. It would be just as easy to pass the integer value assigned to this variable as it is to pass its address. Soon, however, your data will be much larger and much more complex than single integers. That’s why we pass addresses. It’s not always possible to pass a copy of data you want to work with, but you can always pass the address of where that data begins. And it’s easy to access data once you have its address.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset