C Programming - Arrays - Discussion

Discussion Forum : Arrays - Find Output of Program (Q.No. 2)
2.
What will be the output of the program ?
#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));
        }
    }
    return 0;
}
1, 1, 1, 1
2, 3, 2, 3
3, 2, 3, 2
4, 4, 4, 4
1, 2, 1, 2
2, 3, 2, 3
3, 4, 3, 4
4, 2, 4, 2
1, 1, 1, 1
2, 2, 2, 2
2, 2, 2, 2
3, 3, 3, 3
1, 2, 3, 4
2, 3, 4, 1
3, 4, 1, 2
4, 1, 2, 3
Answer: Option
Explanation:
No answer description is available. Let's discuss.
Discussion:
78 comments Page 7 of 8.

Shubham said:   1 decade ago
Can anyone please explain static int a[2][2] = {1, 2, 3, 4}; ?
Also static int *p[] = {(int*)a, (int*)a+1, (int*)a+2};

Aabid khan said:   1 decade ago
I could not get the logic of this question please explain.

Trupti said:   1 decade ago
You are absolutely right @Paul.
If
static int *p[] = {a, a+1,a+2};
then o/p is:

1 1 1 1
2 3 2 3
3 2 3 2
4 4 4 4

Paul said:   1 decade ago
This is a terrible and confusing example for anyone!

It is a 2-dimensional array so (a + 1) would point to the first element of the second row, which is 3, and (a + 2) would point to the third row but in this case there is no third row.

Only because a, a+ 1 and a + 2 are cast to integer pointers in the line : static int *p[] = {(int*)a, (int*)a+1, (int*)a+2}, this means they increments by the size of an integer, therefore the next element in the array instead of the next row.

Anyone else agree?

Rashmi said:   1 decade ago
Can anyone tell me.

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

What is meant by last line?

Vinod said:   1 decade ago
Substitute p=1 and i and j as 00,01,10,11 in all the arrays condition in printf.

So that for i=0 and j=0, p=1(every time) we get it as 1111.

Repeat the procedure for all. The answer is correct only.

Sourabh said:   1 decade ago
What may be the answer if we solve it by as two dimensional array?

Reena said:   1 decade ago
@Anushu.

The answer correct is:

1111
2222
2222
3333

The given answer is correctly.

Charan said:   1 decade ago
a[2][2] is an array stores all elements which is 2D (2-rows,2-columns).

column 0 1

0 row---1 2
1 row---3 4

int *a gives the base address of the first element.
int *a+1 gives the base address of the second element.
int *a+2 gives the base address of the third element.

All the base address are stored in the pointer *p[].

*p[0] gives 1 , *p[1] gives 2 ,*p[2] gives 3.

If we print *p then it will show the base address.

**p --- gives the value 1.

Arun said:   1 decade ago
Why more operators are used in variable?

Does it show different meaning?


Post your comments here:

Your comments will be displayed after verification.