#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?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With