In this code at line number 7, 'p' is a 1D pointer then how come at the print statement it is being considered as 2D pointer ? and when we do 'a+1' then it would cross whole array. I am not able to understand this code. Please explain. Expected output is
1 1 1 1
2 3 2 3
3 2 3 2
4 4 4 4
But I am getting
1 1 1 1
2 2 2 2
2 2 2 2
3 3 3 3

#include<stdio.h>

int main()
{
        static int a[2][2]={1,2,3,4};
        int i,j;
        static int *p[]={(int*)a, (int*)a+1, (int*)a+2};

        for(i=0;i<2;i++)
        {
                for(j=0;j<2;j++)
                {
                    printf("%d %d %d %d \n", *(*(p+i)+j), *(*(j+p)+i), *(*(i+p)+j), *(*(p+j)+i));
                }
        }
}

Order of operations, my friend. (int*)a + 1 converts a to a pointer to int, then increments it as a pointer to int. What you wanted, according to your expected output, was to increment a first, then convert to a pointer to int:

static int *p[] = {(int*)a, (int*)(a + 1), (int*)(a + 2)};

Notice the parentheses around a + 1 and a + 2.

Edited 3 Years Ago by deceptikon

Thanks for the reply deceptikon.
But what about this ?

*(*(p+i)+j)

p is an array of pointers. *(p+i) could be written as p[i] and *(p[i] + j) could likewise be written as p[i][j]. (So *(*(p+i)+j) could be written as p[i][j]) (and the contents of p are offsets off a which is 2-dimensional)

So you could write that printf as: printf("%d %d %d %d \n", p[i][j], p[j][i], p[i][j], p[j][i]);.

You could also declare the array a as static int a[4]={1,2,3,4};.

You could see
p[0] as {1, 2, 3, 4}
p[1] as {2, 3, 4}
p[2] as {3, 4}
p[3] as {4}

You loops request

p[0][0], p[0][0], p[0][0], p[0][0],
p[0][1], p[1][0], p[0][1], p[1][0],
p[1][0], p[0][1], p[1][0], p[0][1],
p[1][1], p[1][1], p[1][1], p[1][1]

which results in:

1, 1, 1, 1
2, 2, 2, 2
2, 2, 2, 2
3, 3, 3, 3

Edited 3 Years Ago by Gonbe

This question has already been answered. Start a new discussion instead.