Drone6251
Drone6251

Reputation: 128

Different Results When Printing Element of Integer Pointer Different Ways

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;
}

Upvotes: 1

Views: 155

Answers (3)

Hatted Rooster
Hatted Rooster

Reputation: 36463

Other answers already touched on what the problem is here, I want to emphasize that your code is anti-modern C++, you should really be using std::vector (or std::array if you have C++11) which will solve all of these things instantly:

#include <vector>

std::vector<int> toBinary(int i) {

    std::vector<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;
}

And then..

std::vector<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;

Upvotes: 4

BDL
BDL

Reputation: 22167

The toBinary method returns the address of a local variable. byte will be deleted when the function exits.

The fact that your first output works seems to be just luck because the memory segment wasn't used by anything else at that point.

To fix this, you'll either have to allocate the array on the heap manually or you use one of the containers (std::array, std::vector).

Upvotes: 7

Pushan Gupta
Pushan Gupta

Reputation: 3825

Through toBinary you are returning a local variable that gets freed once the function call ends. You must allocate memory for the array using heap. And then return that pointer and collect it in the variable b.

Upvotes: 3

Related Questions