-3

I see this in the code and can't understand what is going here:

T * ptr; // we have some pointer and it has proper adress
...
// Later I see this and I can't understand what is going here
ptr = *((T **)ptr);

Also, later in the code I see *((T**)ptr) = m_address;

What for this construction is used ? *((T**)ptr)

Thanks!

Bill Lumbert
  • 4,633
  • 3
  • 20
  • 30
  • It's casting. We are saying that - hey consider this address as `T**` and then dereference it. – user2736738 Feb 25 '18 at 11:48
  • Do you know about *casting*? Do you know about *pointer dereferencing*? Read about them in your text books. – Some programmer dude Feb 25 '18 at 11:48
  • De-referencing type-casted pointer? – machine_1 Feb 25 '18 at 11:49
  • Duplicate of [in-c-if-i-cast-dereference-a-pointer-does-it-matter-which-one-i-do-first](https://stackoverflow.com/questions/4634252/in-c-if-i-cast-dereference-a-pointer-does-it-matter-which-one-i-do-first) Duplicate of [why-cast-to-a-pointer-then-dereference](https://stackoverflow.com/questions/39312058/why-cast-to-a-pointer-then-dereference/39312134) – user2736738 Feb 25 '18 at 11:50
  • @coderredoc so why don't you hammer this? – Jean-François Fabre Feb 25 '18 at 11:51
  • @Jean-FrançoisFabre.: Because it involved 2 tags. If someone has different opinion let me know. Will open it. – user2736738 Feb 25 '18 at 11:52
  • the OP kind of spammed tags. This isn't C++, this is plain C unless proven otherwise. Don't be shy about the hammering, don't wait to get [tag:pointers] gold badge to close this :) – Jean-François Fabre Feb 25 '18 at 11:57

1 Answers1

1

It means that the author wished they'd written T** ptr instead, and are hacking around the fact that they didn't, by casting the pointer to a different type than that which it was declared with, before dereferencing it. It pretends that ptr points to T** instead of a T*.

There are some occasions on which this type punning is okay (e.g. it's commonly used with the struct sockaddr type to sort of implement polymorphism), but type punning T* to T** is very strange.

In fact, unless T is char, or T has a T* as its first member and there's no padding, it's also a code smell (and, as far as I'm aware, UB).

Avoid.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055