Jordan
Jordan

Reputation: 305

Pointer Manipulation? C++

Can someone please tell me what line 2 is doing here? I checked to see if it was just assigning the address of a to b but it isn't.

int a = 5, *b;
b = (int*) a;

Upvotes: 0

Views: 470

Answers (1)

Read some good C++ programming book about type casts and pointers.

So on the second line, a contains 5. You are casting it to a pointer (to int) with (int*)a. This gives some (invalid) pointer containing the address 5.

on some free standing C++ runtime environments - perhaps some cheap microcontroller - the address 5 might be meaningful and legitimate (but even that is very unlikely for 5). But usually not on hosted C++ environments (e.g. compiling on and for Linux, Windows, MacOSX, Hurd, ...)

As soon as you would dereference that pointer (e.g. with int c= *b;), you'll get undefined behavior, very often some segmentation fault

You might want b = &a; as commented by technusm1

Upvotes: 2

Related Questions