-1

I wanted to pass an array by reference in a function from another function. Here is my code below

// Objectives:
// 1. Passing an array to a method
// 2. Returning arrays from a method

#include <iostream>
using namespace std;

int getArray(int* arr) {
    for (int i=0; i< 11; i++) {
        cout << arr[i] << endl;
    }
    return 0;
}

int* returnArray() {
    int arr [11] = {1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21};
    return arr;
}

int main() {
    getArray(returnArray());
    return 0;
}

Here is my output:

get_return_array.cpp:17:12: warning: address of stack memory associated with local variable 'arr' returned
      [-Wreturn-stack-address]
return arr;
           ^~~
1 warning generated.
1
32767
170167402
1
9
11
2051556088
32767
17
9
1436251616

Why values of array are some garbage values and what does the warning signifies?

Marked as duplicate, why??: I have shown usage of static with explanation while the others' answer haven't.

3
  • is that for some sort of comunity wiki? what's the point of ignoring the explicit warning? Commented Oct 15, 2016 at 7:23
  • No, you're not passing the array by reference. Commented Oct 15, 2016 at 7:24
  • you are not passing the get function your array, you are just passing the pointer to the first element of your array Commented Oct 15, 2016 at 7:28

1 Answer 1

-1

C++ does not advocate the passing reference of local array to outside function. Lifetime of arr is till it's parent function runs. The values in the stack of arr will be overwritten if any new assignment is done.

So to overcome this restriction we have to use static whose purpose is to allocate values statically so that its lifetime extends till program runs.

That's why array has some garbage values.

The correct program will be

#include <iostream>
using namespace std;

int getArray(int* arr) {
    for (int i=0; i< 11; i++) {
        cout << arr[i] << endl;
    }
    return 0;
}

int* returnArray() {
    static int arr [11] = {1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21};
    return arr;
}

int main() {
    getArray(returnArray());
    return 0;
}

It's corresponding output is:

1
3
5
7
9
11
13
15
17
19
21

Cheers

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

2 Comments

it's important that the API of the function tells explicitly that the array cannot be shared between threads for instance. It's not thread safe or reentrant. The correct way to do this if you tag this question C++ would be to return a vector, then you wouldn't worry about the allocation/deallocation.
@Jean-FrançoisFabre I haven't used thread in my example.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.