Pointer Outlaw

Hi people C:

I'm playing with pointers again. I need help with this code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>

using namespace std;


int main()
{
    const float pi = 3.14;
    const float *pointer1 = &pi;
    float *pointer2;
    pointer2 = (float*)pointer1;

    *pointer2 = 6.28;

    if(pointer1 == pointer2)
        cout << "hehe, pointer1 points to the same spot as the pointer2\n";

    cout << *pointer2 << ' ' << *pointer1 << ' ' << pi;

    return 0;
}


The output I get is:

hehe, pointer1 points to the same spot as the pointer2
6.28 6.28 3.14


Why does the changed value pointed by "pointer1" print (6.28), but when I try to access the original variable, I still get the unchanged value (3.14)?
Shouldn't "*pointer1" and "pi" print out the same value, because they access the same part of the memory? I'm confused.

Thanks in advance :)
Last edited on
closed account (3hM2Nwbp)
One does not simply cast away constness and expect anything good to happen.

Try a C++ style cast and see what you get. C-style casting should not be done in C++ code...

pointer2 = static_cast<float*>(pointer1);

Hey...that gives me an idea...

http://i.imgur.com/bTtM4iY.jpg
Last edited on
Hahaha, nice one.

I didn't know there was a difference between C-style and C++-style cast.
I learned something new ^_^ Thank you.
Topic archived. No new replies allowed.