使用函数时出现 cout 错误

cout error while using functions

我在尝试使用函数创建将十进制数转换为二进制数的代码时遇到了问题。起初我只使用 main 函数创建代码并且它运行良好,但决定修改它以使用函数。我相信代码编写正确,但是当我尝试 cout 我的答案时,我得到了一个很大的数字,比如 115120160758866453687091316369641637416

这是代码

  #include <iostream>
    #include <math.h>

    using namespace std;
int* unsigned_dec(int dec_M) { //function for converting absolute part of          numbers

    int bin[8] = { 0,0,0,0,0,0,0,0 };
    int ind = 7;
    int arr_ind = 0;
    for (int base = (int)abs(dec_M); base > 0; base = base / 2) {

        if (base % 2 == 0) {

            bin[arr_ind] = 0;
            ind--;
        }
        else {
            bin[arr_ind] = 1;
            ind--;
        }
        arr_ind++;
    }
    return bin;

}


int main() {// main function
    int dec_N;
    cin >> dec_N;
    int* bin_main = unsigned_dec(dec_N); //we are not sure if we are     assigning the returned value of function to array in correct  

for (int i = 0; i <= 7; i++) {

        cout << bin_main[i];
}
cout << endl;

return 0;
}

然后我尝试将 cout 代码更改为

cout << bin_main[0] << bin_main[1] << bin_main[2] << bin_main[3] << bin_main[4] << bin_main[5] << bin_main[6] << bin_main[7] << endl;

这很好用。 然后我以其他方式编写了相同的 cout 的第二个变体

cout << bin_main[0];
cout << bin_main[1];
cout << bin_main[2];
cout << bin_main[3];
cout << bin_main[4];
cout << bin_main[5];
cout << bin_main[6];
cout << bin_main[7];
cout << endl;

我的代码开始 cout 同一个陌生号码。我认为 couts 的所有 3 种方式都几乎相同(尤其是 2 和 3),但不明白是什么让它不起作用。

int bin[8] = { 0,0,0,0,0,0,0,0 };

stack 上分配。您应该在堆

上分配 bin
auto bin = std::unique_ptr<int, std::default_deleter<int[]>>(new int[8]);

甚至更好,使用 std::vector

您正在返回指向 unsigned_dec 中 int</code>bin[] 的局部数组的指针。一旦 <code>main 中的另一个函数被调用,即 cout operator .

,函数 unsigned_dec 堆栈上的数组将失效

正如其他人已经提到的:函数永远不应该 return 指向局部变量的指针。当函数 returns.

时局部变量无效

更好的方法是使用向量,并将函数 return 设为向量。

类似于:

#include <iostream>
#include <math.h>

using namespace std;

//function for converting absolute part of numbers
vector<int> unsigned_dec(int dec_M) {
    vector<int> bin;   // Create a vector
    bin.resize(8, 0);  // Fill it with 8 elements initialized to zero

    int arr_ind = 0;
    // Note: added check for arr_ind being valid
    for (int base = (int)abs(dec_M); base > 0 && arr_ind < 8; base = base / 2) {
        if (base % 2 == 0) {
            bin[arr_ind] = 0;
        }
        else {
            bin[arr_ind] = 1;
        }
        arr_ind++;
    }
    return bin; // Return the vector
}


int main() {
    int dec_N;
    cin >> dec_N;
    vector<int> bin_main = unsigned_dec(dec_N);
    for (int i = 0; i < bin_main.size(); i++) {
        cout << bin_main[i];
    }
    cout << endl;

    return 0;
}