C Programming - Pointers - Discussion

Discussion Forum : Pointers - Find Output of Program (Q.No. 13)
13.
What will be the output of the program?
#include<stdio.h>

int main()
{
    int arr[3] = {2, 3, 4};
    char *p;
    p = arr;
    p = (char*)((int*)(p));
    printf("%d, ", *p);
    p = (int*)(p+1);
    printf("%d", *p);
    return 0;
}
2, 3
2, 0
2, Garbage value
0, 0
Answer: Option
Explanation:
No answer description is available. Let's discuss.
Discussion:
87 comments Page 9 of 9.

Rupinderjit said:   1 decade ago
Viraj is right.

If you want to get 3 as output, use (p+2) and proper typecasting.

Because: p+1 points to upper byte of 3 as per little-endian method, which is 0 (00000000 00000011) and p+2 points to 3, lower bye of three (00000000 00000011).

Vanni said:   1 decade ago
I didn't get this one can anyone explain me?

Vivek said:   1 decade ago
char p stored in int type arr. which is not possible without conversion.

Abhishek.e.k said:   1 decade ago
p = (char*)((int*)(p));
even without this line program will run fine

Swati said:   1 decade ago
It gives error "cannot convert 'int*' to 'char*'" in both lines

p=arr;
p=(int*)(p+1);

Puru said:   1 decade ago
p = (char*)((int*)(p));
// till now the pointer p is type casted to store the variable of type character.

printf("%d, ", *p); // %d means integer value so value at first address i.e. 2 will be printed.

p = (int*)(p+1); // here p is still of type character as type casted in step 1 so p(i.e address) and plus 1 will increase only by one byte so

as per viraj suggested

Assuming that integer requires 2 bytes of storage
the integer array will be stored in memory as


value 2 3 4
address 00000010 00000000 00000011 00000000 00000100 00000000
pointer p+1


so p+1 points to that location which is unfilled as during intialization 2,3,4 were stored in variable of type integer(2 bytes).

so p+1 will point to 00000000.

(int*)p+1 // p+1 is type casted again to integer

printf("%d", *p); // this will print 0 as output as by default integer contains 0 as value.

Puru said:   1 decade ago
@viraj accepted your idea. its the same


Post your comments here:

Your comments will be displayed after verification.