8
Addresses and Pointers

Your computer is, at its core, a processor (the Central Processing Unit or CPU) and a vast meadow of switches (the Random-Access memory or RAM) that can be turned on or off by the processor. We say that a switch holds one bit of information.You’ll often see 1 used to represent on and 0 used to represent off.

Eight of these switches make a byte of information. The processor can fetch the state of these switches, do operations on the bits, and store the result in another set of switches. For example, the processor might fetch a byte from here and another byte from there, add them together, and store the result in a byte way over someplace else.

Figure 8.1  Memory and the CPU

Memory and the CPU

The memory is numbered, and we typically talk about the address of a particular byte of data. When people talk about a 32-bit CPU or a 64-bit CPU, they are usually talking about how big the address is. A 64-bit CPU can deal with much, much more memory than a 32-bit CPU.

Getting addresses

In Xcode, create a new project: a C Command Line Tool named Addresses.

The address of a variable is the location in memory where the value for that variable is stored. To get the variable’s address, you use the & operator:

#​i​n​c​l​u​d​e​ ​<​s​t​d​i​o​.​h​>​

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​;​
 ​ ​ ​ ​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​"​,​ ​&​i​)​;​
 ​ ​ ​ ​r​e​t​u​r​n​ ​0​;​
}​

Notice the %p token. That’s the token you can replace with a memory address. Build and run the program. You’ll see something like:

i​ ​s​t​o​r​e​s​ ​i​t​s​ ​v​a​l​u​e​ ​a​t​ ​0​x​b​f​f​f​f​7​3​8​

although your computer may put i at a completely different address. Memory addresses are nearly always printed in hexadecimal format.

In a computer, everything is stored in memory, and thus everything has an address. For example, a function starts at some particular address. To get that address, you just use the function’s name:

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​;​
 ​ ​ ​ ​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​"​,​ ​&​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.

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

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