简体   繁体   中英

How can an declare an array in a function that returns an array in c++

// 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM