0

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!

3 Answers 3

1

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).

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for you quick reply ...can you please explain me how is it working....thanks!
1
#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?

Comments

0

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].

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.