Pointer to Pointer in Objective-C
Last Updated :
17 Mar, 2023
Pointers in Objective-C are a powerful and essential concept for any programmer to master. Pointers allow you to manipulate data stored in memory directly and are used to store the address of a variable. Pointer-to-pointer also known as a double pointer, is a type of pointer that holds the address of another pointer. The pointer-to-pointer concept is often used in situations where you need to pass a pointer as an argument to a function or to store a dynamically allocated object.
There are three types of pointers in Objective-C: a regular pointer, a pointer to constant, and a constant pointer. A regular pointer holds the address of a variable, while a pointer to a constant holds the address of a constant value. A constant pointer holds a constant address and cannot be changed.
Pointer to Pointer
A pointer to pointer, or double pointer, is a type of pointer that holds the address of another pointer. A double pointer is declared using two asterisks (**) in the declaration, such as int p, where p is a double pointer. The first asterisk (*) represents the type of data stored at the address held by the pointer, and the second asterisk () represents that it is a pointer to a pointer.
Syntax:
The syntax for declaring a pointer-to-pointer is similar to that of a regular pointer, with two asterisks used to indicate that it is a pointer to a pointer.
data_type **pointer_name;
Example: int **p;
Here, pointer to pointer includes &, *, and **. The & operator is used to get the address of a variable, while the * operator is used to access the value stored at the address held by the pointer. The ** operator is used to access the value stored at the address held by a pointer to a pointer.
Example 1:
ObjectiveC
#import <Foundation/Foundation.h>
void swap( int **p, int **q)
{
int *temp = *p;
*p = *q;
*q = temp;
}
int main( int argc, const char * argv[])
{
NSAutoreleasePool * pool = [[ NSAutoreleasePool alloc] init];
int a = 10, b = 20;
int *p = &a, *q = &b;
NSLog ( @"Before Swapping" );
NSLog ( @"Value of a = %d" , a);
NSLog ( @"Value of b = %d" , b);
swap(&p, &q);
NSLog ( @"\nAfter Swapping" );
NSLog ( @"Value of a = %d" , *p);
NSLog ( @"Value of b = %d" , *q);
[pool drain];
return 0;
}
|
Output:
Before Swapping
Value of a = 10
Value of b = 20
After Swapping
Value of a = 20
Value of b = 10
Example 2: Using pointer to pointer to dynamically allocate memory.
ObjectiveC
#import <Foundation/Foundation.h>
int main()
{
int i = 5;
int *p;
int **q;
p = &i;
q = &p;
NSLog ( @"Value stored at i = %d" , i);
NSLog ( @"Value stored at *p = %d" , *p);
NSLog ( @"Value stored at **q = %d" , **q);
return 0;
}
|
Output:
Value stored at i = 5
Value stored at *p = 5
Value stored at **q = 5
Share your thoughts in the comments
Please Login to comment...