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 The first is in the declaration where you declare the variable addressOfI to be an int *. That is, it is a pointer to a place where an int can be stored.

The second is where 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.

Don’t worry if you don’t have pointers squared away in your mind just yet. We’ll spend a lot of time working with pointers in this book, so you’ll get plenty of practice.

Now let’s make a common programming mistake. Remove the * from the fourth line of main() so that it reads

 ​ ​ ​ ​a​d​d​r​e​s​s​O​f​I​ ​=​ ​8​9​;​

Notice Xcode pops up a warning that says Incompatible integer to pointer conversion assigning to 'int *' to 'int'. Fix the problem.

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

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