Channels ▼
RSS

Tools

Pointers in Objective-C


Christopher Fairbairn and Collin Ruffenach are the authors of Objective-C for the iPhone.


Within Objective-C, the use of object-oriented programming is, in fact, optional. Since Objective-C is based upon C foundation, it is possible to use C-style functions. However Objective-C's full power is only unlocked if you make full use of its object-oriented extensions.

In this article, we will discover some of the benefits of object-oriented development. Let's take a look at one of the most basic concepts of object-oriented programming. A variable within an application can be considered to consist of four components. These are its:

  • Name
  • Location -- where it is stored in memory
  • Type -- what kind of data it can store
  • Current value

Understanding where variables are located and if it is possible to access them by means other than their name is closely related to the concept of pointers.

Memory Maps

You can consider the memory of the iPhone as being made up of a large pile of bytes, each stacked one on top of another. Each byte has a number, called an address, associated with it, just like houses have an associated street number. Figure 1 represents several bytes of the iPhone's memory, starting at address 924 and extending through address 940.

Figure 1: A sample snapshot of a region in the iPhone's memory showing the location of variable x.

When you allocate a variable within your application, the compiler reserves an explicit amount of memory for it. For example, a statement such as int x = 45 will cause the compiler to reserve 4 bytes of memory to store the current value of x. This is represented in figure 1 by the 4 bytes starting at address 928.

Obtaining the Address of a Variable

Referring to the name of a variable within an expression will access or update its current value. By placing the address-of (&) operator in front of a variable name we are able to learn the address at which the variable is currently stored.

A variable that is able to store the address of another variable is called a "pointer". This is because the variable is said to point to the location of another value. The following code snippet demonstrates how we can use the address-of operator:


int x = 45; 
int* y = &x; 

This code snippet declares an integer variable x that is initialized to the value 45. It also declares variable y with a data type of int*. The * at the end of the data type indicates a pointer and means we do not want to store an actual integer value but rather the memory address at which one can be found. This pointer is then initialized with the address of variable x using the address-of operator. If variable x had been stored at address 928 (as previously mentioned), we could graphically represent the result of executing this code snippet by updating the memory map to be similar to that in Figure 2.

Figure 2: An updated memory map showing how variable y stores the address of variable x.

Notice how the 4 bytes allocated to store variable y now store the number 928. When interpreted as an address, this indicates the location of variable x, as indicated by the arrow. The expression b>y = &x can be read as "place the address of variable x into variable y". Following a pointer Once you have an address stored within a pointer variable, it is only natural to want to determine the value of whatever it points at. This operation is called dereferencing the pointer and is also achieved using the * symbol, as demonstrated below.


int x = 45; 
int *y = &x; 
NSLog(@"The value was %d", *y); 

The statement on the last line will print out the message "The value was 45" since the * in front of variable y causes the compiler to follow the pointer and access the value it currently points at. Instead of reading the value it is also possible to replace it, as demonstrated below. Confusingly this also makes use of the * operator:


int x = 45; 
int *y = &x; 
*y = 92; 

The statement on the last line stores the value 92 at the address located within variable y. Referring to Figure 2, you will see that variable y stores (or points to) address 928; hence, executing this statement actually updates the value of variable x, even though x is never explicitly referred to within the statement.


Arrays Are Pointers In Disguise

A variable identifier for a C-style array can at some level be thought of as a simple pointer. This pointer always points to the first element within the array. As an example, the following is perfectly valid Objective-C source code.


int ages[50]; 
int* p = ages; 
NSLog(@"Age of 10th person is %d", p[9]); 

Notice that we can assign the array variable to a pointer variable directly without the use of the & operator, and we can use the familiar [] syntax to calculate an offset from the pointer. A statement such as p[9] is simply another way to express *(p + 9). In other words, p[9] is a shorthand way to say, "Add 9 to the pointer's current value and then dereference it".


When working with pointers to structure-based data types a special dereferencing syntax allows you to deference the pointer and access a specific field within the structure in a single step. To do this we use the -> operator, as demonstrated below:


struct box * p = ...; 
p->width = 20; 

The -> operator demonstrated on the second line dereferences the pointer p and then accesses the width field within the structure. While following a pointer to read or alter the value it points at, it is also helpful at times to compare two pointers to check if they point to identical values.


Related Reading


More Insights






Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

 
Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.
 

Video