Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is `*((char*)ptr+4))` doing? [closed]

#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?

like image 532
dpaksp Avatar asked May 12 '26 00:05

dpaksp


2 Answers

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.

like image 103
Jerry Coffin Avatar answered May 13 '26 16:05

Jerry Coffin


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

like image 33
Amarghosh Avatar answered May 13 '26 16:05

Amarghosh