0

I have an 2-D array and i wanted to access the particular element of this array using pointer to array something like this below

 main()
 {
  int a[][4]={{2 ,0 ,0 ,2},{41 ,0, 0, 9}};

  int (*p)[4]=a;
  printf("%d",*p[0]);
  }

This gives me the first element of Ist 1-d array but now access 2nd element of 1-d array using pointer to array?

1
  • No i tried it already it gives me 1st element of 2nd 2-D array Commented Jan 4, 2012 at 10:51

4 Answers 4

1

You can simply access the elements of your 2d arrays like this:

printf("%d", a[0][1]); /* prints second item of first array */
Sign up to request clarification or add additional context in comments.

Comments

1

a[x][y] gets compiled into *(a+x*4+y).

Comments

0

The elements are accessed using the corresponding row and column numbers.

If u have to access the second element of the first row in the 2-D array mentioned above, then you can use

printf("%d",a[2][1]);

Comments

0
int a[2][4]={{2 ,0 ,0 ,2},{41 ,0, 0, 9}};
int (*p)[4]=a;

for (i = 0; i < 2; i++)
    for (j = 0; j < 4; j++)
        printf("%d\n", p[i][j]);

You can access the array elements with p as if it was a. The reason for that is simply because when you use the name a in a value context, its type is already int (*)[4], so the same type as p.

Note that the p[i][j] form in C is equivalent to *(*p + i) + j).

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.