Objective-C: Pointer

Pointers are variables that stores address of another variable.

Declaring Pointers

Pointers are declared by using * symbol as prefix of the variable, for example,

int *apointer;

 In the above statement, apointer is a pointer to type-integer.

 

Working

To better understand how pointers work, let us consider a program where,

var is an integer variable

*ptr is pointer to an integer type

 

Program:

 #import <Foundation/Foundation.h>

int main (int argc, const char *argv[])

{

 int var = 5;    // A simple variable declaration

 int *ptr;   // A pointer is declared

 ptr = &var; // Pointer stores address of variable  

 NSLog(@”The value of variable var = %i”,var);

 NSLog(@”The address of variable var = %i”,&var);

 NSLog(@”The value at pointer ptr = %i”,*ptr);

 NSLog(@”The address stored at pointer ptr = %i”,ptr);

 return 0;

}

 

 Output:

 

 The value of variable var = 5

The address of variable var = 2030

The value at pointer ptr = 5

The address stored at pointer ptr = 2030

In the above program,

  • Variable var is initialized as an integer with value 5.
  • A pointer variable ptris declared.
    • Whenever a value is assigned to any variable, a memory is allocated to that variable where value is stored and a pointer can hold that memory address.

Here, ptr holds address of variable var.