Kishore Suthar
Kishore Suthar

Reputation: 2983

Issue with NSArray Address

I'm trying to print memory address of array but i'm getting same memory address for all three array Let me explain more I have taken three array

NSArray *arr1 = [[NSArray alloc]init];
NSArray *arr2 = [[NSArray alloc]init];
NSArray *arr3 = [[NSArray alloc]init];

when i'm printing memory address

NSLog(@"arr1 = %p, arr2 = %p, arr3 = %p", arr1, arr2, arr3);

all memory address same

Output:

arr1 = 0x7f9c01d21550, arr2 = 0x7f9c01d21550, arr3 = 0x7f9c01d21550

but when i print memory address with this code

NSLog(@"arr1 = %p, arr2 = %p, arr3 = %p", &arr1, &arr2, &arr3);

Memory address is diffrent

Output:

arr1 = 0x7fff5fb8e338, arr2 = 0x7fff5fb8e330, arr3 = 0x7fff5fb8e328

I don't know why first NSLog print same address. Thanks in advance for your help

Upvotes: 1

Views: 50

Answers (1)

gnasher729
gnasher729

Reputation: 52530

The first NSLog printed the arrays. The second NSLog printed the addresses of the three variables where the arrays were stored. For the second NSLog you would have got the same result even if you never assigned an array.

The reason why the first NSLog prints the same address three times is that [[NSArray alloc] init] will always return an identical object. Call [[NSArray alloc] init] a billion times and only one NSArray object will ever be created. Since an NSArray is immutable, and you can never add anything to this empty array, why should the OS waste space to allocate more than one array? (This is actually a very useful optimisation if you have many empty arrays).

Upvotes: 2

Related Questions