dhrtzzz dhrtzzz - 2 months ago 13
C Question

Explain the output of this program of this code?

// Explain the output of this code,specifically can't understand the last printf output...Please explain

int a1[]={6,7,8,18,34,67};
int a2[]={23,56,28,29};
int a3[]={-21,27,-31};
int *x[]={a1,a2,a3};

void print(int *a[])
{
printf("%d",a[0][2]); // outputs 8
printf("%d",*a[2]); //outputs -21
printf("%d",*++a[0]); //outputs 7
printf("%d",*(++a)[0]); //outputs 23
printf("%d",a[-1][+1]); /*outputs 8 explain?*/

}

main()
{
print(x);
return(0);
}

Answer

Remember that a is a pointer to a pointer and may be changed, it isn't the same object as the array x, it merely points to the first element of that array. The same holds for the elements of array x, they are just pointers to arrays a1, a2, a3.

Before the last printf line, the pointer a points to the second element of the array x, which is a pointer to the array a2. The cause for this is the fourth printf line which incremented the pointer a by one.

Then we step into the last printf line.

The first subscript [-1] decrements the pointer a, the result now points to the first element of the array x, which is a pointer to the array a1. The dereference gives the value of that pointer. Because of the third printf line, this pointer points to the second element of the array a1.

The second subscript [1] retrieves the the third element of array a1.