polslinux
polslinux

Reputation: 1779

pointers and cast

Let's take this example code:

#include <stdio.h>

int main(void){
    int x = 1;
    if(*(char *)&x == 1) printf("little-endian\n");
    else printf("big-endian\n");
    return 0;
}

I have seen this (or similar one) instruction *(char *)&x multiple times and now i want to completely understand what does it mean!
I think it means:
1) take the address of the int variables
2) then cast it to a char pointer
3) then compare the first element of the "new char pointer" with the number 1.

Am i right?

Upvotes: 7

Views: 191

Answers (1)

unwind
unwind

Reputation: 400109

You're about right, but a better listing would be:

  1. Take the address of x
  2. Convert address into a pointer to character
  3. Dereference that pointer, i.e. read the first char at &x
  4. Compare character value to integer 1

Note that this is rather edgy code, the read value will depend on the machine's byte endianness.

Upvotes: 5

Related Questions