D
drowned
I'm having a problem understanding why the code in this little program
I've got is behaving the way it does... if anyone can explain it, I'd
be grateful:
#include <iostream>
using namespace std;
//This function takes an unsigned char (one byte on my machine)
//and prints it in binary notation
void printBinary(const unsigned char val) {
for(int i = 7; i >= 0; i--)
if(val & (1 << i))
std::cout << "1";
else
std::cout << "0";
}
int main() {
float f=1;
unsigned char uc = (unsigned char) &f;
unsigned char* ucp = &uc;
for(int i=0;i<sizeof(float);i++) { //sizeof(float) == 4
cout << "ucp[" << i << "] = " << (long)ucp << endl;
cout << "ucp[" << i << "] = "; printBinary(ucp); cout << endl;
}
}
If I understand what is going on here correctly, I am taking the
address of the float and casting it to an unsigned char. I then assign
that value to the unsigned char pointer. When I change the value of
the float, however, ucp's value changes. I would think that ucp would
not change because it holds an address... what does changing the value
of the float have to do with its address?
I've got is behaving the way it does... if anyone can explain it, I'd
be grateful:
#include <iostream>
using namespace std;
//This function takes an unsigned char (one byte on my machine)
//and prints it in binary notation
void printBinary(const unsigned char val) {
for(int i = 7; i >= 0; i--)
if(val & (1 << i))
std::cout << "1";
else
std::cout << "0";
}
int main() {
float f=1;
unsigned char uc = (unsigned char) &f;
unsigned char* ucp = &uc;
for(int i=0;i<sizeof(float);i++) { //sizeof(float) == 4
cout << "ucp[" << i << "] = " << (long)ucp << endl;
cout << "ucp[" << i << "] = "; printBinary(ucp); cout << endl;
}
}
If I understand what is going on here correctly, I am taking the
address of the float and casting it to an unsigned char. I then assign
that value to the unsigned char pointer. When I change the value of
the float, however, ucp's value changes. I would think that ucp would
not change because it holds an address... what does changing the value
of the float have to do with its address?