I'm wondering why new doesn't seem to retain the array information and just returns an int*:
#include <iostream>
using namespace std;
typedef int (*p_to_array)[80];
typedef int arr[80];
int main()
{
arr a;
p_to_array p = &a; //fine
p_to_array p2 = new arr; // incompatible types
return 0;
}
In addition to dynamically allocating single values, we can also dynamically allocate arrays of variables. Unlike a fixed array, where the array size must be fixed at compile time, dynamically allocating an array allows us to choose an array length at runtime.
Dynamic memory allocation is the process of assigning the memory space during the execution time or the run time.
What is a Dynamic Array? A dynamic array is quite similar to a regular array, but its size is modifiable during program runtime. DynamArray elements occupy a contiguous block of memory. Once an array has been created, its size cannot be changed.
A dynamic array is similar to an array but it's size is dynamic and so it will grab more memory when it is full and you add a new element to it. They can be created on the stack or on the heap. A dynamically allocated array is simply an array that is created on the heap.
I might be totally wrong about this: (i.e. this is little more than an educated guess)
new arr;
is equivalent to:
new int[80];
which by language rules returns int*
.
From cppreference.com: (thanks to @interjay for pointing out I actually cited the irrelevant part)
The new-expression returns a prvalue pointer to the constructed object or, if an array of objects was constructed, a pointer to the initial element of the array.
My understanding of that is that when allocating an array, the new[]
form will be picked. The only thing your example changes is the syntax; it doesn't make the language treat arrays as non-arrays (regular objects).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With