3,254 views
0 0 votes
#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+2);
    printf("%d", *p);

    return 0;
}

Pls explain the output and also the code

2 Answers

Best answer
2 2 votes

NOTE: Output will vary for different size of int.

Assuming that integer requires 2 bytes 

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


 till now the pointer p is type casted to store the variable of type character right?

This is wrong, Type Casting donot change the Size of pointer. 

means if it would have been p=((int*)p); instead of  p = (char*)((int*)(p)); result would be same.


printf("%d, ", *p); // output : 2

integer array will be stored in memory MSB to LSB as

00000000 00000100 00000000 00000011 00000000 00000010
                    4                      3                      2




so p+2 points to that location  00000011.

printf("%d", *p); // output : 3

so answer is 2 3

• edited by
0 0 votes

its answer 2,3 because if type casting occur then in this case 

in case of  fisrt *p then it catch only on byte due to char type  and in general computer big indian format is aaply so first is LSB=2 then msb=0 hence lsb value 2

and other case means int*(p+2 )then in this case access 1 byte due to  it access 3 aacording to big indian format

Position:
Show:

Related questions

1 1 vote
1 1 answer
172
172 views
khanshahima4 asked Sep 24
172 views
1. If precedence tells me which operator has priority, and associativity tells me how to handle operators at the same level, then why do I need a separate concept called ...
13 13 votes
1 1 answer
1.3k
1.3k views
GO Classes asked Jul 2
1,267 views
Assume:$\texttt{short = 2 bytes}$, $\texttt{int = 4 bytes}$, $\texttt{char = 1 byte}$$\texttt{int}$ needs $4$-byte alignment and the final structure size is rounded to a ...
16 16 votes
2 2 answers
683
683 views
GO Classes asked Jul 2
683 views
Assume:struct Student { double gpa; }; struct Student alice; struct Student *sptr = &alice;Which of the following correctly assigns $\texttt{4.0}$ to $\texttt{alice.gpa}$...
9 9 votes
1 1 answer
511
511 views
GO Classes asked Jul 2
511 views
Consider the following code idea from the source:typedef struct { double x, y; } Point; void reset(Point p) { p.x = p.y = 0; } int main() { Point a = {12.0, 42.0}; Point ...