Getting the data at an address

If you have an address, you can get the data stored there using the * operator. Have the log display the value of the integer stored at addressofI.

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​)​;​
 ​ ​ ​ ​p​r​i​n​t​f​(​"​t​h​e​ ​i​n​t​ ​s​t​o​r​e​d​ ​a​t​ ​a​d​d​r​e​s​s​O​f​I​ ​i​s​ ​%​d​​n​"​,​ ​*​a​d​d​r​e​s​s​O​f​I​)​;​
 ​ ​ ​ ​r​e​t​u​r​n​ ​0​;​
}​

Notice that the asterisk is used two different ways in this example:

  • When you declared addressOfI to be an int *. That is, you told the compiler It will hold an address where an int can be stored.

  • When you read the int value that is stored at the address stored in addressOfI. (Pointers are also called references. Thus, using the pointer to read data at the address is sometimes called dereferencing the pointer.)

You can also use the * operator on the left-hand side of an assignment to store data at a particular address:

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​)​;​
 ​ ​ ​ ​*​a​d​d​r​e​s​s​O​f​I​ ​=​ ​8​9​;​
 ​ ​ ​ ​p​r​i​n​t​f​(​"​N​o​w​ ​i​ ​i​s​ ​%​d​​n​"​,​ ​i​)​;​
 ​ ​ ​ ​r​e​t​u​r​n​ ​0​;​
}​

Build and run your program.

Do not worry if you do not have pointers squared away in your mind just yet. You will spend a lot of time working with pointers as you go through this book, so you will get plenty of practice.

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

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