Jhansi Rani
Jhansi Rani

Reputation: 449

Does typecasting have no effect in statement 1 in the below Code?

#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); //............statement 1
    printf("%d", *p);
    return 0;
}

In the above code, p = (int*)(p+1); means character pointer is type cast to integer pointer. So when we dereference p, It fetches the contents up to next int size (2 bytes or 4 bytes, depending on compiler). But when I am solving this question at www.indiabix.com, they have given

answer: 2, 0

How it can be 2, 0? As per my analysis,the answer should be 2, 3. Can anyone explain what should be the correct answer and why?

Upvotes: 0

Views: 269

Answers (1)

R Sahu
R Sahu

Reputation: 206637

Let's say an int takes four bytes.

In a little endian system, the memory layout of arr looks like:

|   | <--- one byte
+---+---+---+---+---+---+---+---+---+---+---+---+
| 2 | 0 | 0 | 0 | 3 | 0 | 0 | 0 | 4 | 0 | 0 | 0 |
+---+---+---+---+---+---+---+---+---+---+---+---+

In a big endian system, the memory layout of arr looks like:

|   | <--- one byte
+---+---+---+---+---+---+---+---+---+---+---+---+
| 0 | 0 | 0 | 2 | 0 | 0 | 0 | 3 | 0 | 0 | 0 | 4 |
+---+---+---+---+---+---+---+---+---+---+---+---+

In a little endian system,

*p = 2;
*(p+1) = 0;

In a big endian system,

*p = 0;
*(p+1) = 0;

Depending on your platform, the output will be:

2 0

or

0 0

The code you have is perhaps meant to confuse. The line

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

doesn't do a damn thing.

The line

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

has the same effect as:

p = p+1;

Upvotes: 2

Related Questions