0

I am new to C++. I am trying to define a binary converter function and return a pointer. Then U want to display generated binary in the main function:

#include <iostream>
using namespace std;

int* binary_con(int n)
{
    int i;
    int binary[100];
    for (i = 0; n > 0; i++)
    {
        binary[i] = n % 2;
        n = n / 2;
    }
    return binary;
}

int main()
{
    int n;
    int* a;
    cout << "Input the number:";
    cin >> n;
    a = binary_con(n);

    while (*a)
    {
        cout << *a;
        a++;
    }
    return 0;
}

But after I run my code, I got this:

enter image description here

Can anyone explain this to me?

8
  • 1
    One bug is return binary; you can't return a pointer to an array. The array no longer exists when the binary_con() function ends. Commented Oct 26, 2021 at 11:28
  • 1
    See also: stackoverflow.com/questions/6441218/… Commented Oct 26, 2021 at 11:28
  • 2
    You also don't initialize the array and would only print ones, encountering a zero stops the printout. Which is not ideal for binary, the occasional zero is needed as well. Commented Oct 26, 2021 at 11:29
  • 2
    Using a vector instead of an array would solve both these problems. Commented Oct 26, 2021 at 11:31
  • You could also have the function output a std::string if all you are going to do is print the result. Commented Oct 26, 2021 at 11:32

1 Answer 1

0

you can't return an array from a function, the way is to pass that array as an argument to the functionm using this approach:

void binary_con(int n, int *binary)

now you have access to binary array inside your function, hence you can edit it and see the changes outside of the function without returning anything.

inside your main, instead of writing a = binary_con(n);, you should write this: binary_con(n, a);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.