Typecasting Pointers in C++

Written by Ali on. Posted in C++

Typecasting as earlier discussed is a powerful tool and demands extreme care when being handled. Typecasting pointers in C has to be dealt with the same level of care. The language allows typecasting to be handled efficiently even by the pointers, allowing a very versatile usage of pointers and making the code user efficient. Meanwhile, the pointers as discussed earlier can be very tricky to handled at times and a single mistake can send the code crashing or possibly memory leak.

Though there’s nothing much new about typecasting with pointers other than we previously discussed, typecasting with pointers demand a bit of care as there is much more risk of having run time errors. The pointers follow the same rules of typecasting as there were in explicit typecasting, implicit typecasting and type promotion. Typecasting a value form int to float can probably give warnings in some casino online compilers, may not be bothered by some, but it is better to know what is happening in the code. For an idea of such an example, just take a look at the following piece of code:

</p>
<p>int main()</p>
<p>{</p>
<p>int * a = new int;</p>
<p>* a = 12;</p>
<p>&nbsp;</p>
<p>float * c = new float;</p>
<p>*c = 113.11;</p>
<p>&nbsp;</p>
<p>int * b = new int;</p>
<p>* b = (int) *c;</p>
<p>&nbsp;</p>
<p>cout &lt;&lt; *b;</p>
<p>delete a;</p>
<p>delete b;</p>
<p>delete c;</p>
<p>&nbsp;</p>
<p>return 0;</p>
<p>}</p>
<p>

In the first two lines, memory is being allocated to the integer pointer ‘a’ and then the number 12 is being stored to that allocated memory. A float type pointer ‘c’ is declared and a dynamic memory is allocated to it, in which the value 113.11 is stored. Now the type casting occurs in the following code where an int pointer ‘b’ is made. After allocating memory to ‘b’, the value of float type ‘c’ is being stored in ‘b’ by being explicit typecasting. The value of “c” would be 113.11, what would be the value of “b” ? In the end, it is better to delete the memory allocated dynamically so as to return the system its resources.

That”s all for now people, stay tuned for the next post.

Tags: , ,

Trackback from your site.

Leave a comment