views:

150

answers:

3
#include<stdio.h>
main()
{
  int a[]={0,2,4,6,8};
  int *ptr;
  ptr=a;
  printf("%d", *((char*)ptr+4));
}

*((char*)ptr+4)) What is the purpose of this?

+2  A: 

ptr initially points to the first value of the array. (char*)ptr casts it from int* to char*. Adding 4 to this char* value increments it by 4 * sizeof(char) making it point to the second integer of the array, assuming 32 bit (4 byte) int and one byte char on a little endian platform. The outer * dereferences it and hence the output 2.

Had you not cast it to char* - as in *(ptr+4) - it would have added 4 * sizeof(int) to the pointer and hence you'd have gotten 8, (a[4]) as the output.


Update: have some fun!

#include<stdio.h>
main()
{
    int a[]={0x00010203, 0x04050607};
    int *ptr;
    int i, j;
    ptr=a;
    for(i = 0; i < 2; i++) {
        for(j = 0; j < 4; j++)
            printf("%d", *((char*)ptr + 4 * i + j));
        printf("\n");
    }
}

I got the output:

3210
7654

If you try this on a big endian machine, you'd get

0123
4567

Read more about endianness

Amarghosh
The answer will only be 2 on a little-endian 32 bit platform. On a big-endian platform you'll get 0.
Jason Williams
@Jason thanks; updated!
Amarghosh
A: 

since ptr points to the address of a, it

*ptr is the first value of a, or 0.

By casting ptr to a char* and adding 4, the code is saying "take the address that ptr stores, add 4 to it, then print the value at this location.

In this example, it should print 2

Alan
+3  A: 

It's casting the pointer to be viewed as a pointer to char, then adding 4 to look at something 4 char's later in memory, and finally dereferencing the result. In a typical case where int occupies 4 bytes, it'll look at the first byte of the second int in the array. That char will be promoted to an int, passed to printf, and printed out.

Jerry Coffin