Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Cast void* to T* const

I have a void* pointer p that points to an array of data whose type is T (mostly float), I want to update data using this pointer p, so I cast it with reinterpret_cast<T*>(p) and then modify the values. The problem is, p itself must not be modified, so for safety I really want to cast it to T* const, but I don’t know how to do it properly.

T* const cp = reinterpret_cast<T* const>(p);
T* const cp = static_cast<T* const>(p);
T* const cp = static_cast<T* const>(reinterpret_cast<T*>(p));
....

I know the easiest way is to make a copy of p and use that copied pointer instead, so that the original p never gets modified, just wonder how I can achieve the same thing by casting.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Casting a pointer will create a new pointer value which is separate and distinct from the old one. p will not be affected, period. So there’s no need to play around with const here.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading