Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ type casting with pointers

I come from a background of C# and Java and I can't seem to understand what casting with pointers means in C++.

For example:

int x = 1;
char c = *((char*)&x);

What does it do? What it is useful for?

like image 719
UnTraDe Avatar asked Dec 09 '22 22:12

UnTraDe


2 Answers

In both your examples you're making mistakes making the code not compile. So I'll assume you're trying to do the following:

int x = 1;
char c = *((char*)&x);

Depending on your architecture, c will now have either the value of the least or the most significant byte of x. In this example this would be either 0 or 1 (this can actually be used to detect the byte ordering).

Your second example won't work, cause you're trying to ignore the const resulting in an illegal operation/bad cast (this is also called "const correctness").

Edit: Regarding your comment about "what does it mean?":

In expressions: &somevariable will return the address of somevariable. *somevariable will assume the contents of somevariable are the address of the actual value, which is then returned.

In declarations: datatype is a normal variable/object. This is passed "by value". datatype& is a reference. This works exactly like normal variables in Java/C# and is passed by reference. datatype* is a pointer. This just contains the address where the actual value is located (see above) and is essentially passed by reference as well.

Actual casts work pretty much similar to Java/C#, but pointers are just that: They point to the location of the actual value. While this might confuse you, pointers in C/C++ work pretty much like the standard variables/references used in Java/C#.

Look at this:

MyClass x; // object of MyClass
MyClass *x; // pointer to an object of MyClass - the actual value is undefined and trying to access it will most likely result in an access violation (due to reading somewhere random).
MyClass *x = 0; // same as above, but now the default value is defined and you're able to detect whether it's been set (accessing it would essentially be a "null reference exception"; but it's actually a null pointer).
MyClass &x = MyClass(); // creating a new reference pointing to an existing object. This would be Java's "MyClass x = new MyClass();"
like image 101
Mario Avatar answered Dec 27 '22 01:12

Mario


Casting in C++ works just like casting in Java, no pointers involved.

int x = 1;
char c = (char) x; // Lose precision

However, what you are doing here:

int x = 1;
char *c = (char *)x;

is telling the compiler that the value of x is the address of a character. It is equivalent to

char *c;
c = 1; // Set the address of c to 0x0000000000000001

There are very few times you need to do this.

like image 44
Lex R Avatar answered Dec 26 '22 23:12

Lex R