What it means *(int *)

Asked

Viewed 12,821 times

7

I’m reading a code that has things like.

  *(int *)ptrArray = intN;
  *(float *)ptrArray= floatN;

It is clear that different types are being assigned to the same type vector void*. The question is, what is the meaning of *(int *) or *(float *)?

2 answers

4


Let’s say I have a pointer to a whole

int* iPtr;

Whereas it already points to a valid memory address, if I want to change the value of it I first need to override the pointer

*iPtr = 100; //atribuo o valor 100

So this * is what indicates that I am slipping this pointer and assigning the value to the memory to which it points, if I did not have the * there I would be trying to change the address to which this pointer points

But this works because the compiler knows the type, when using void* you own a generic pointer, as if you don’t have a defined type you can’t simply override this pointer, so you first need to cast it for another type of pointer so you can override it, whereas we have a variable void* voidPtr, in the example

*(int*)voidPtr = 100;

First the (int*) does the cast of void* for int*, then the first * melts the pointer to assign the value

  • Now it all makes sense! Thanks.

1

Expressions should be read as follows::

1) The value of ptrArray, I’m treating like a pointer to int, receives intN (which is a int)

1) The value of ptrArray, I’m treating like a pointer to float, receives floatN (which is a float)

This happens because you want to put a value (and not an address) in the place pointed by ptrArray, which is a pointer to an undefined type data sequence (void*). So, we need the forced conversion before the variable name, or the compiler will point to an error.

GCC 4.9.2 would say: error: invalid use of void expression

  • This I understand that happens, what I want to know is what the syntax means. Mainly why * before casting (int*).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.