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?

Rizwan
  • 103
  • 4
  • 24
Yanbo Liu
  • 15
  • 4
  • 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. – drescherjm Oct 26 '21 at 11:28
  • 1
    See also: https://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope –  Oct 26 '21 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. –  Oct 26 '21 at 11:29
  • 2
    Using a vector instead of an array would solve both these problems. – interjay Oct 26 '21 at 11:31
  • You could also have the function output a std::string if all you are going to do is print the result. – drescherjm Oct 26 '21 at 11:32
  • Please don't post pictures of text, post text as text. You were able to post your code as text, so you should also be able to post your output as text. – Jabberwocky Oct 26 '21 at 11:32
  • Did you read the compiler warning `warning C4172: returning address of local variable or temporary: binary`? – Jabberwocky Oct 26 '21 at 11:34
  • Also Related to returning an array: [https://stackoverflow.com/questions/61802165/how-can-an-declare-an-array-in-a-function-that-returns-an-array-in-c](https://stackoverflow.com/questions/61802165/how-can-an-declare-an-array-in-a-function-that-returns-an-array-in-c) – drescherjm Oct 26 '21 at 11:38

1 Answers1

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

hessam_kk
  • 310
  • 1
  • 12