2

How do i access the array in the main using the reference arrref

The memory leak in the code below is intended to know valgrind tool.But i am not able to compile the code below

#include <iostream>
int& func();
int main() 
{

    int &arrref = func();
    std::cout<<arrref[1];//Error
    std::cout<<&arrref[1];//Error
}

int& func()
{

    int *a = new int[10];
    for(int i = 0;i<10 ;++i)
            a[i] = i*2;
    return *a;

}

Thanks

ildjarn
  • 62,044
  • 9
  • 127
  • 211
user2256825
  • 594
  • 6
  • 22

2 Answers2

0

The syntax needed is (&arrref)[1]. That refers to the second element of an array.

But make sure that the reference returned from func indeed refers to the first element of an array with sufficient number of elements.

To communicate clearly that func returns a reference to an array you may like to return a range, e.g.:

#include <iostream>
#include <boost/range/as_array.hpp>

boost::iterator_range<int*> func() {
    static int array[2] = {1, 2};
    return boost::as_array(array);
}

int main() {
    auto array = func();
    std::cout << array[0] << '\n';
    std::cout << array[1] << '\n';
    for(auto const& value: func())
        std::cout << value << '\n';
}

Outputs:

1
2
1
2
Maxim Egorushkin
  • 131,725
  • 17
  • 180
  • 271
  • 2
    A static array sounds like a horrible idea that will fix a short term problem and lead to long-term problems. – Yakk - Adam Nevraumont Sep 17 '16 at 15:46
  • @EdHeal May be you would like to elaborate on what is going to happen to an array of POD with static storage duration in a multi-threaded program? – Maxim Egorushkin Sep 18 '16 at 13:30
  • Two threads accessing and using the same data at the same time. Can get very strange results – Ed Heal Sep 18 '16 at 13:31
  • @Yakk _and lead to long-term problems._ - may be it will, may be it won't, the correct answer - it depends. – Maxim Egorushkin Sep 18 '16 at 13:32
  • @EdHeal Sorry to break it on you, but multiple threads accessing the same object do not cause any issues, as long as there is no race condition. – Maxim Egorushkin Sep 18 '16 at 13:35
  • If you aim a loaded gun at someone and pull the trigger, maybe it will shoot and kill them. I mean, it could jam or it could be a dud bullet, what *actually* happens, it depends. You give an exampke on stack overflow where you recommend returning a reference to a static local array for no good reason, maybe you'll get downvoted. The correct answer - it depends. – Yakk - Adam Nevraumont Sep 18 '16 at 13:36
  • @Yakk You missed the point, which is _To communicate clearly that func returns a reference to an array you may like to return a range_. – Maxim Egorushkin Sep 18 '16 at 13:37
  • @MaximEgorushkin - Eh? An object has multiple variables (in this case items in the array). Those values may have implications and semantics on the other values. In a multi-threaded environment you can get the object in an inconsistent state. That is why we have mutex – Ed Heal Sep 18 '16 at 13:39
  • No, I read the point, understood the point, judged the answer including the context, found it overall harmful, pointed out the problem, got dismissed with waffle, then downvoted and explained why. – Yakk - Adam Nevraumont Sep 18 '16 at 13:41
  • @Yakk Your original comment is irrelevant and is just scaremongering. We agree to disagree. – Maxim Egorushkin Sep 18 '16 at 13:47
-1

Firstly it is not a good idea access local variables of one function in some other functions. The function return type is int& which says that you want to return a reference to an int variable. If you want to access the array local array 'a' then the function should be rewritten as -

 #include <iostream>
 int* func();

  int main() 
  {

  int *arrref = func();
   std::cout<<arrref[1];//Error
  std::cout<<&arrref[1];//Error


  }

  int *func()
 {

     int *a = new int[10];
     for(int i = 0;i<10 ;++i)
        a[i] = i*2;
     return a;

  }

Alternatively you can also use vectors -

  #include<iostream>
  #include<vector>
  std::vector<int>& func();

  int main() 
  {

    std::vector<int>& arrref = func();
    std::cout<<arrref[1];//Error
    std::cout<<&arrref[1];//Error


   }

   std::vector<int>& func()
   {

    std::vector<int> a(10);
    for(int i = 0;i<10 ;++i)
        a[i] = i*2;
    return a;

    }
GAURANG VYAS
  • 689
  • 5
  • 16
  • I think `std::vector func()` is better. I think (but not sure) `std::vector& func()` may be undefined behaviour – Ed Heal Sep 18 '16 at 13:15
  • No i just tried it. And gave no undefined behaviour. – GAURANG VYAS Sep 18 '16 at 13:18
  • You cannot just try it once to determine it it is undefined behavior. I think it is because you are giving a reference to something that is on the stake. I am 99.999% sure that this is undefined behavior. – Ed Heal Sep 18 '16 at 13:19
  • Please see http://stackoverflow.com/questions/3252292/c-return-reference-stack-memory et al. – Ed Heal Sep 18 '16 at 13:22
  • In my answer i already mentioned that accessing local variable of one function in some other function is not a good idea . So surely the above method is not valid. I am just telling one of the efficient methods to do the same. I agree that it might show undefined behaviour but it also answers the above question. – GAURANG VYAS Sep 18 '16 at 13:25
  • Your code (answer) does have undefined behaviour. Remove the reference from the return type of `func` – Ed Heal Sep 18 '16 at 13:30