01.02.2014 Views

Objective-C Fundamentals

Objective-C Fundamentals

Objective-C Fundamentals

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

60 CHAPTER 3 An introduction to objects<br />

Figure 3.2<br />

variable x<br />

An updated memory map showing how variable y stores the address of<br />

This code snippet declares an integer variable x that’s initialized to the value 45. It<br />

also declares variable y with a data type of int *. The * at the end of the data type indicates<br />

a pointer and means you don’t want to store an actual integer value but rather<br />

the memory address at which one can be found. This pointer is then initialized with<br />

the address of variable x via use of the address-of operator. If variable x had been<br />

stored at address 928 (as previously mentioned), you could graphically represent the<br />

result of executing this code snippet by updating the memory map to be similar to<br />

that shown in figure 3.2.<br />

Notice how the 4 bytes allocated to store variable y now store the number 928.<br />

When interpreted as an address, this indicates the location of variable x, as indicated<br />

by the arrow. The expression y = &x can be read as “place the address of variable x into<br />

variable y.”<br />

3.3.3 Following a pointer<br />

Once you have an address stored in a pointer variable, it’s only natural to want to<br />

determine the value of whatever it points to. This operation is called dereferencing the<br />

pointer and is also achieved by using the * symbol:<br />

int x = 45;<br />

int *y = &x;<br />

NSLog(@"The value was %d", *y);<br />

The statement on the last line prints out the message "The value was 45" because the<br />

* in front of variable y causes the compiler to follow the pointer and access the value it<br />

currently points to. In addition to reading the value, it’s possible to replace it, as demonstrated<br />

next. Confusingly, this operation also makes use of the * operator:<br />

int x = 45;<br />

int *y = &x;<br />

*y = 92;<br />

The statement on the last line stores the value 92 at the address located in variable y.<br />

Referring to figure 3.2, you’ll see that variable y stores (or points to) address 928, so<br />

executing this statement updates the value of variable x even though x is never explicitly<br />

referred to in the statement.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!