Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic array allocation

Tags:

c++

arrays

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;
}
like image 790
LogicBreaker Avatar asked Jan 12 '15 11:01

LogicBreaker


People also ask

Can we allocate array dynamically?

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.

What is dynamic allocation explain?

Dynamic memory allocation is the process of assigning the memory space during the execution time or the run time.

What is dynamically allocated array in C++?

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.

What are the differences between array and dynamic allocation?

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.


1 Answers

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

like image 129
Bartek Banachewicz Avatar answered Nov 01 '22 09:11

Bartek Banachewicz