I have an integer array: int* b whose values are set for elements 0 through 7. When I print out each element individually, I get the correct elements. However, when I use a for loop, I am getting different results. Any idea why?
Here's the code:
//toBinary(int x) returns an int pointer whose value is an array of size 8: int ret[8]
int* b = toBinary(55);
//Print method 1 (Individual printout)
cout << b[0] << b[1] << b[2] << b[3] << b[4] << b[5] << b[6] << b[7] << endl;
//Print method 2 (for loop)
for (int t = 0; t < 8; t++)
cout << b[t];
cout << endl;
The result of the first print out is the following: 00110111
This is the correct printout.
When I print using the second technique, it says, -858993460-85899346051202679591765470927361022170810222364 This is the wrong printout.
Why am I getting two different printouts?
Here is the toBinary method:
int* toBinary(int i) {
int byte[8];
for (int bit = 7; bit >= 0; bit--) {
if (i - pow(2, bit) >= 0) {
byte[7-bit] = 1;
i -= pow(2, bit);
}
else
byte[7-bit] = 0;
}
return byte;
}
toBinaryimplemented?