Header Ads

Pointer To An Array - Objective C

 It is most likely that you would not understand this post until you through the post related to Pointer in Objective C.

So, assuming you have a bit understanding on pointer in Objective C programming language, let us start. An array name is  a constant pointer to the first element of the array. Therefore, in the declaration.:

double balance[50];


balance is a pointer to &balance[0], which is the address of the first element of the array balance. Thus, the following program fragment assigns p the address of the first element of balance.

double *p;
double balance[10];

p = balance ;
 

It is legal to use array names as constant pointers and vice versa. Therefore, *(balance + 4) is a legitimate way of accessing the data of  balance[4].

Once you store the address of first element in p, you can access array element using *p, *(p+1), *(p+2) and so on. Below is the example to show all the concept discussed in this post.

#import <Foundation/Foundation.h>
int main()
{
    //an array with 5 element
    double balance[5] = {1000.0, 2.0, 3.4, 17.0 , 50.0 };
    double *p;
    int i;
   
    p = balance;
   NSLog(@"Array values using pointers\n");
   for(i=0; i<5; i++)
   {
         NSLog(@"*(p+%d) : %f\n", i , *(p+i));
   }
   NSLog(@"Array values using balance as address\n");
   for(i=0; i<5; i++)
   {
        NSLog(@"*(balance + %d) : %f\n", i, *(balance + i));
    }
   return 0;
}

In the above example, p is a pointer to double, which means it can store address of a variable of double type. Once we have address in p, then *p will give us value available at the address stored in p.


No comments:

Powered by Blogger.