Return by address from Learncpp, me confused

Hi folks,

I'm failing to get my head around the following code from Learncpp.com:
1
2
3
4
5
6
7
8
9
10
11
12
13
int* AllocateArray(int nSize)
{
    return new int[nSize];
}
 
int main()
{
    int *pnArray = AllocateArray(25);
    // do stuff with pnArray
 
    delete[] pnArray;
    return 0;
}


What is the function "AllocateArray" returning? Just a memory address of an array containing 25 elements? But where is the array? What's it's name? If i understand right, the code allocates some memory for a non-existant array!?.........i don't geddit!!

If someone could shine some light on this, i'd be very grateful!
Here's the relevant page link:
http://www.learncpp.com/cpp-tutorial/74a-returning-values-by-value-reference-and-address/
Last edited on
It seems that your confusion comes from not understanding what the new or new[] keywords do. You should learn that first if you want to understand this code.

Note that in modern C++ (specifically, C++14 and later) you should have almost no reason to ever write new or new[] because of the standard library containers and smart pointers.
Many thanks, i re-read the Learncpp lesson about "new int" and now i understand the code snippet!
:)
Last edited on
Topic archived. No new replies allowed.