0

// functions that converts a number into an array

int *initialiser(int number)
{
    int array[20];

    for (int i = 19; i >= 0; i--)
    {
        array[i] = number % 10;
        number /= 10; // number = number/10
    }

    return array;
}

//I get this error

primaryAddSub.cpp: In function 'int* initialiser(int)':
primaryAddSub.cpp:21:9: warning: address of local variable 'array' returned [-Wreturn-local-addr]
     int array[20];
         ^~~~~

I can use static int array[20]; but the function will return the same result each time I call it.

8
  • 3
    Use a std::array or a std::vector instead. Commented May 14, 2020 at 16:12
  • thanks and how can i return this type please? Commented May 14, 2020 at 16:14
  • 1
    std::array<int, 20> initialiser(int number) Commented May 14, 2020 at 16:15
  • or std::vector<int> initialiser(int number) { std::vector<int> array(20); ... } and the rest would work too. Only the call site would perhaps need some adjustment - depending on what it looks like now. Commented May 14, 2020 at 16:16
  • 4
    @user4581301 Arrays are always passed by reference WAT??? Arrays decay to a pointer and that pointer is passed by value. To pass an array by reference, you need to explicitly do so like void foo(int (&x)[100]); Commented May 14, 2020 at 16:21

1 Answer 1

1

As the comment says, prefer to use a std::vector instead of an int*. An example of how this works would be:

std::vector<int> initialiser(int number)
{
    std::vector<int> array;

    // ... fill up array

    return array;
}

If you absolutely want to return an int*, then as the error says, you are returning a pointer to a local variable. You need to allocate memory instead:

int *initialiser(int number)
{
    int *array = new int[20];

    // ... fill up array 

    return array;
}

Don't forget to delete this memory when you are done with it. Also, the caller really has no way to know how many elements are in the array, so they might read/write out of bounds.

In general this is error prone, so prefer the first version, then you don't have to worry about deleting anything, and are less likely to make out of bounds errors.

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

2 Comments

you are a life and time saver thanks alot....it took me hours but I didn,t find any solution. Thanks again
No worries, glad to help. Please do take the suggestion about using vector instead, even if the array version is working now for you.

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.