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.

Thanks for the reply deceptikon.
But what about this ?

*(*(p+i)+j)

What about it?

P is 1D pointer but here being treated as 2D ?

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

Thanks a ton Gonbe :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.