user4097971
user4097971

Reputation:

2 dimensional array in pointers

#include<stdio.h>
void main()
{
    int a[] = { 1, 2, 3, 4 };
    int b[] = { 5, 6, 7 };
    int *p[2];
    p[0] = a;
    p[1] = &b + 1;
    printf("%d\n%d", &p[1][0], p[0][1]);
}

Here p is a 1d array of pointers, then how come a 2d array is used in the printf statement. Also the output is 1 2.

Upvotes: 0

Views: 157

Answers (2)

John Bode
John Bode

Reputation: 123468

The subscript operator [] is defined for pointer expressions as well as array expressions (which are implicitly converted to pointer expressions before the subscript is applied).

The expression a[i] is evaluated as *(a + i); a is a pointer, and a + i gives the address of the i'th element of the array (pointer arithmetic is based on the pointed-to type; if a points to an int, then a + i gives the address of the i'th int following the one pointed to by a).

So given your array of pointers:

int *p[2];

the expression p[0] has a pointer type, so you can add an offset and dereference the result: *(p[0] + 1), which is the same as writing p[0][1].

Upvotes: 0

Drax
Drax

Reputation: 13288

Here p is a 1darray of pointers

Yep, and you can use the subscript operator ptr[index] with pointers which is equivalent to *(ptr + index)

Thus p[1][0] is the same as *(p[1] + 0) which is the same as *(p[1])

Also your code does not compile for several reasons including void main()


Simple example to illustrate:

int main()
{
  const char *hello = "hello";
  const char *world = "world";

  const char *array[2] = {hello, world};

  char e = hello[1]; // char e now contains 'e'
  e = array[0][1]; // same thing as previous line

  char r = world[2]; // char r now contains 'r'
  r = array[1][2]; // same thing as previous line
}

Upvotes: 2

Related Questions