What does * (int *) mean?

7

I'm reading a code that has stuff like that.

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

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

    
asked by anonymous 09.11.2015 / 14:09

2 answers

4

Let's say I have a pointer to an integer

int* iPtr;

Given that it already points to a valid memory address, if I want to change the value of it I need to first derrefer the pointer

*iPtr = 100; //atribuo o valor 100

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

But this works because the compiler knows the type, when you use void* you have a generic pointer, since you do not have a defined type you can not simply derrefer this pointer, so you first need to cast it to a another type of pointer to be able to derrefer it, considering that we have a void* voidPtr variable, in the example

*(int*)voidPtr = 100;

First the (int*) cast void* to int* , then the first * derreferences the pointer to be able to assign the value

    
09.11.2015 / 18:06
1

The expressions should be read as follows:

1) The value of ptrArray , which I am treating as a pointer to int , gets intN (which is int )

1) The value of ptrArray , which I am treating as a pointer to float , gets floatN (which is float )

This happens because you want to put a value (not an address) in the place indicated by ptrArray , which is a pointer to a data stream of undefined type ( 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

    
09.11.2015 / 14:48