c++pointersreference

How to pass a pointer to a function and allocate and initialize it


I want to send a null pointer to a function as a reference, then allocate and initialize it there as

#include <iostream>

void foo(int*& p)
{
   p = new int(20);
   for (int i = 0; i < 20; ++i){
      *(p+i) = i;
      std::cout << *(p+i) << std::endl;
   }
}

int main()
{
   int* p = nullptr;

   foo(p);

   for (int i = 0; i < 20; ++i)
      std::cout << *(p+i) << std::endl;
}

But this code result in something really strange, the result is

0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
0
1
2
3
4
5
6
7
657975
668983
10
11
12
13
14
15
16
17
18
19

The values in function foo is correct but in main on arrays v[7] and v[8] have strange values. I could not understand its behavior.


Solution

  • Actually, you don't create an array of 20 int but only one int; you have to write p = new int[20]; instead.

    #include <iostream>
    
    void foo(int*& p)
    {
       p = new int[20]; // we create an array of 20 ints
       for (int i = 0; i < 20; ++i){
          *(p+i) = i;
          std::cout << *(p+i) << std::endl;
       }
    }
    
    int main()
    {
       int* p = nullptr;
    
       foo(p);
    
       for (int i = 0; i < 20; ++i)
          std::cout << *(p+i) << std::endl;
    }
    

    Demo