Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pointers and cast

Tags:

c

pointers

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?

like image 422
polslinux Avatar asked Sep 03 '12 08:09

polslinux


People also ask

Can you typecast a pointer?

We saw that pointer values may be assigned to pointers of same type. However, pointers may be type cast from one type to another type. In the following code lines, A is an int type variable, D is variable of type double, and ch is a variable of type char.

What is type cast in c programming?

Type casting is the process in which the compiler automatically converts one data type in a program to another one. Type conversion is another name for type casting. For instance, if a programmer wants to store a long variable value into some simple integer in a program, then they can type cast this long into the int.


1 Answers

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.

like image 93
unwind Avatar answered Sep 29 '22 00:09

unwind