Mar 2, 2013

Pointers and Arrays

In previous post – Pointers – we discussed very simple examples of pointers. Here we will try and understand pointers & arrays again with very simple examples.

Example 1 of Pointers & Arrays

In this example we are declaring an array and printing the first value in an array. First value in an array starts from index 0.

#import <Foundation/Foundation.h>
int main (int argc, char *argv[])
{
int arr[5]={1,2,3,4,5};
NSLog (@"value of arr[0] %i", arr[0]);
return 0;
}

Output:
value of arr[0] 1

Example 2 of Pointers & Arrays

Another array example in which we are printing all the values of an array.

#import <Foundation/Foundation.h>
int main (int argc, char *argv[])
{
int arr[5]={1,2,3,4,5}, i;

for (i=0; i<=4;i++)
NSLog (@"value of element %i= %i",  i, arr[i]);
return 0;
}

Output:
value of element 0= 1
value of element 1= 2
value of element 2= 3
value of element 3= 4
value of element 4= 5

Example 3 of Pointers & Arrays

In this example we are printing address of each element of an array with the help of “address of” operator.

example_3a

Output:
value of element 0= 2293544
value of element 1= 2293548
value of element 2= 2293552
value of element 3= 2293556
value of element 4= 2293560

Example 4 of Pointers & Arrays

Printing each value of an array using *, indirection operator or “value at address” operator.

example_4a

Output:
value of element 0= 1
value of element 1= 2
value of element 2= 3
value of element 3= 4
value of element 4= 5

Example 5 of Pointers & Arrays

On line number 6, we are assigning the starting address or address of 0th element of an array to pointer variable. On line number 9, we are printing each value of an array using *, indirection operator or “value at address” operator.

#import <Foundation/Foundation.h>
int main (int argc, char *argv[])
{
int arr[5]={10,20,30,40,50}, i;
int *p;
p=arr;

for (i=0; i<=4;i++)
NSLog (@"value of element %i= %i",  i, *(p+i));
return 0;
}

Output:
value of element 0= 10
value of element 1= 20
value of element 2= 30
value of element 3= 40
value of element 4= 50

Pages:1234567...22»