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 5 of 9.

Sanjoy said:   1 decade ago
What is type casted?

Vaibhav said:   1 decade ago
p = (int*)(p+1) ; what it does actually ?

Varni said:   1 decade ago
Why not upper byte of 2 not considered here ? (00000000).

Is it put at the end of the array ?

Manishj said:   1 decade ago
It gives warning as incompatible pointer type.

Answer 2, 0 is correct.

It doesn't show errors.

Balu said:   1 decade ago
Assume ,

arr[0] = 1000.
arr[1] = 1004.
arr[2] = 1008.

now,

p=arr; i.e p=1000.

p = (char*)((int*)(p));

At this statement character pointer p 1st typecasted to integer pointer and again typecasted to character pointer.

printf("%d, ", *p);-prints value 2.

As memory representation for little endian (lowest byte will stored 1st).

00000010 00000000 00000000 00000000

p = (int*)(p+1);-in this statement p which is char pointer is incremented by one so it is pointing at location 1001.

printf("%d", *p);-prints value 0 because at memory location 1001 value 0 is stored (according to little endian ).

Mohit said:   1 decade ago
There is a warning of converting int* to char* but, there is no error. Actually we do not follow such coding practice but for the question answer is 2, 0.

Aakash Gupta said:   1 decade ago
In borland and turbo c++ it gives the error: Cannot Convert "int*" to "char*".

Praveen kumar said:   1 decade ago
since integer requires 4 bytes=32 bits so 2,3,4 stored as
==>{lsb first then msb}
00000000 00000000 00000000 00000010 00000000 00000000 00000000
103 102 101 100 107 106 105
00000011 00000000 00000000 00000000 00000100
104 111 110 109 108

Initially,p holds address=100
So value at addr 100=2.

Now,it casted to char ptr,
So int*(p+1) =value at addr 100+1=0.

Sarala said:   1 decade ago
It causes a compile time error as it is an incompatible type conversion p being an character pointer is referring to int base array.

Rookie said:   1 decade ago
It causes a compile time error as it is an incompatible type conversion p being an character pointer is referring to int base array.

Anyone please explain the correct logic.


Post your comments here:

Your comments will be displayed after verification.