Pointer Arithmetic in Objective-C
Last Updated :
26 Apr, 2025
The pointer stores the address of another variable. So that we can perform the arithmetic operations on a pointer. There are four types of operators that can be used in pointer arithmetic ++,--,+, and -. Let's consider that the pointer points integer, which points to address 1000, assuming the integer is 32-bits, so now we perform the following arithmetic operation:
ptr++
Example:
int number = 5;
int *ptr;
// Pointer variable address is 1000
pointer = &number;
/ / Here we use arithmetic operator in pointer variable like this
ptr++;
Now, pointer is point to 1004 address in memory
After completing the above operation, ptr points to 1004 because every time the pointer increment, it will point to the next integer location, which is 4 bytes next to the current location. This pointer points to the next location without impacting the actual value. If the pointer points to a character whose address is 1001 then the next location is 1002 because the character is one byte.
Operations with Pointers
- Increment of a pointer
- Decrement of a pointer
- Addition of integer to a pointer
- Subtraction of integer to a pointer
Increment of a Pointer
The increment of a pointer means when a pointer is incremented it increases by the number equal to the size of the data type for which it is a pointer. For example, suppose we have an integer pointer with the address 2000. Now it incremented by 4(size of the integer) so the new address it will point to is 2004.
Example:
ObjectiveC
// Objective-C program to illustrate pointer to airthmetic
#import <Foundation/Foundation.h>
int main()
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
// Create an array size of five elements
int arr[5] = {59, 43, 32, 24, 13};
// Create a pointer variable with a null initialize
int *pointer = NULL;
// Pass the first element of the address
// in the pointer variable
pointer = arr;
int i;
// Increment the pointer variable
for(i = 0; i < 5; i++)
NSLog(@"Pointer Arithmetic = %d\n", *pointer++);
[pool drain];
return 0;
}
The decrement of a pointer means when a pointer is decremented it decreases by the number equal to the size of the data type for which it is a pointer. For example, suppose we have an integer pointer with the address 2000. Now it decremented by 4(size of the integer) so the new address it will point to is 1996.