Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does *(int*) mean in C++?

Tags:

c++

opengl

I encountered the following line in a OpenGL tutorial and I wanna know what does the *(int*) mean and what is its value

if ( *(int*)&(header[0x1E])!=0  )
like image 725
Valentin Baltadzhiev Avatar asked Oct 03 '13 20:10

Valentin Baltadzhiev


2 Answers

Let's take this a step at a time:

header[0x1E]

header must be an array of some kind, and here we are getting a reference to the 0x1Eth element in the array.

&(header[0x1E])

We take the address of that element.

(int*)&(header[0x1E])

We cast that address to a pointer-to-int.

*(int*)&(header[0x1E])

We dereference that pointer-to-int, yielding an int by interpreting the first sizeof(int) bytes of header, starting at offset 0x1E, as an int and gets the value it finds there.

if ( *(int*)&(header[0x1E])!=0  )

It compares that resulting value to 0 and if it isn't 0, executes whatever is in the body of the if statement.

Note that this is potentially very dangerous. Consider what would happen if header were declared as:

double header [0xFF];

...or as:

int header [5];
like image 102
John Dibling Avatar answered Oct 07 '22 10:10

John Dibling


It's truly a terrible piece of code, but what it's doing is:

&(header[0x1E])

takes the address of the (0x1E + 1)th element of array header, let's call it addr:

(int *)addr

C-style cast this address into a pointer to an int, let's call this pointer p:

*p

dereferences this memory location as an int.

like image 21
Paul Evans Avatar answered Oct 07 '22 09:10

Paul Evans