EZ

Eduzan

Learning Hub

Eduzan
Eduzan / Objective C

Pointers in Objective-C

In Objective-C, pointers are variables that store the memory address of another variable. A pointer variable must be declared before use. The size of a pointer depends on the system architecture. Pointers can be of various data types like charintfloatdouble, or other valid types. They are essential for dynamic memory allocation, as memory cannot be allocated dynamically without them.

Syntax:

type *var-name;

Here, type represents the data type of the pointer, and it must be valid. var-name is the name of the variable, and an asterisk (*) is used to declare the pointer.

Example:

int *ptr;
float *number;
char *mychar;

How to Use Pointers?

Step 1: To use a pointer, start by declaring it with a valid name and data type.

Syntax:

type *var-name;

Example:

int *myPtr;

Step 2: Assign the address of another variable to the pointer using the & (ampersand) operator, which retrieves the variable’s memory address. For instance, &x gives the address of x.

Syntax:

pointer_variable = &var_name;

Example:

myPtr = &x1;

Step 3: To retrieve the value stored at the address, use the * (asterisk) operator.

Syntax:

*var_name;

Example:

NSLog(@"Pointer Value is %d", *myPtr);

Example:

#import <Foundation/Foundation.h>

int main() {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    int a = 50;
    int *ptr;

    ptr = &a;

    NSLog(@"Address of variable a = %p", &a);
    NSLog(@"Address stored in the pointer ptr = %p", ptr);
    NSLog(@"Value of *ptr = %d", *ptr);

    [pool drain];
    return 0;
}

Output:

Address of variable a = 0x16fdff10
Address stored in the pointer ptr = 0x16fdff10
Value of *ptr = 50
End of lesson.