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

igauravsehrawat
  • 3,696
  • 3
  • 33
  • 46

1 Answers1

-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

igauravsehrawat
  • 3,696
  • 3
  • 33
  • 46
  • 1
    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çois Fabre Oct 15 '16 at 07:25
  • @Jean-FrançoisFabre I haven't used thread in my example. – igauravsehrawat Oct 15 '16 at 08:31