Ayesha Nihal
Ayesha Nihal

Reputation: 11

Basic array based, unable to access arrays element?

Hi Friends, I am new to C. I am trying to learn it, I got stuck some where in arrays. Please check following program

#include <stdio.h>
#include <stdlib.h>


int arr1[] = {10,20,30,40,50};
int arr2[] = {5,15,25,35,45};

int *main_arr[] = {arr1,arr2};

int main()
{
 printf("in first array 0th locatin value is: %d\n",*main_arr[0]);
 system("PAUSE");   
 return 0;
}

By using printf i can print the value at 0th location, but not getting how to access rest of the element ...please help me!

Upvotes: 0

Views: 58

Answers (3)

Aniket Inge
Aniket Inge

Reputation: 25733

#include <stdio.h>
#include <stdlib.h>


int arr1[] = {10,20,30,40,50};
int arr2[] = {5,15,25,35,45};

int *main_arr[] = {arr1,arr2};

int main()
{
 int iter1, iter2;
 for(iter1 = 0; iter1 < 2; iter1++){
    for(iter2 = 0; iter2 < 5; iter2++){
        printf("in first array nth locatin value is: %d\n",(main_arr[iter1][iter2]));
    }
 }
 system("PAUSE");   
 return 0;
}

I guess the code is simple enough to be understood?

Upvotes: 1

StarPinkER
StarPinkER

Reputation: 14281

There are only two pointers in the main_arr, pointing to address of arr1 and arr2.

main_arr| ptr to an array | -> arr1
        | ptr to an array | -> arr2

So you can use main_arr[0][1] to access the second element of arr1, because main_arr[0] points to the address of the very first element of arr1.

You should have know that in C, if p is a pointer, then both p[3] and 3[p] will evaluate to *(p + 3 * sizeof(type)), so let's assume p = main_arr[0], then p[1], which is main_arr[0][1], will evaluate to *(main_arr[0] + 1 * sizeof(int)), which is the same value with arr1[1].

Upvotes: 0

Karthik T
Karthik T

Reputation: 31972

You want

...: %d\n",(main_arr[0])[0]);
           -------------      ->arr1
                        ---   ->arr1[0]

main_arr is pointing to both arrays arr1, arr2. So main_arr[0] points to the first element of the first array. To access other elements modify the 2nd [0].

Check it out

The other alternative, uglier but closer to your current code, is to use pointer arithmetic.

...s: %d\n",*(main_arr[0]+1));

Remember that arr[1] is the same as *(arr+1).

Upvotes: 1

Related Questions