0

Is it possible to create a dynamic array in c++ without using a pointer explicitly(int array[] instead of int* array)?

ie. something like this:

int size = 5;
int array[];

array = new int{size};

for (int i = 0; i < size; i++)
{
    array[i];
}
Zzz
  • 2,927
  • 5
  • 36
  • 58
  • 11
    Why not `std::vector`? –  Oct 11 '12 at 21:01
  • You're probably aware of it, but could you not use **std::vector** for this purpose? – Blitzkoder Oct 11 '12 at 21:01
  • Related - [Variable length arrays in C++?](http://stackoverflow.com/questions/1887097/variable-length-arrays-in-c) – Joe Oct 11 '12 at 21:02
  • What are you trying to achieve? You would still have to free it manually, the only difference would be the syntax. Also have look at `std::array`. – Karel Petranek Oct 11 '12 at 21:03
  • Why do you want to do this? I don't get it. You're also implying that you could maybe somehow use a pointer implicitly? What does that even mean? – David Titarenco Oct 11 '12 at 21:06

5 Answers5

2

Yes, of course, it is possible:

#include <iostream>
int main()
{
    [](int array[] = new int[10]) {
        std::cout << "array = " << array << "\n";
        delete[] array;
    }();
}
Dietmar Kühl
  • 150,225
  • 13
  • 225
  • 380
0

In short, no. The compiler needs to know the size of the array, so to use stack allocated arrays in c++, it must be specified in the declaration. I recommend you look at the STL Vector class instead.

jakev
  • 2,815
  • 3
  • 26
  • 39
0

int array[]; necessarily has automatic storage duration (in a function or class scope) and cannot have dynamic storage duration.

You can hide the pointer inside a class like std::vector<int>.

You could do something like

int (&array)[5] = reinterpret_cast<int(&)[5]>(*new int[5]);

to delete: delete [] array;

bames53
  • 86,085
  • 15
  • 179
  • 244
0

You can do it using a reference:

#include <iostream>
using namespace std;

int main()
{
   int& val = *(new int[2]);
   val = 1;
   *(&val + 1) = 2;

   cout << val << ' ' << *(&val+1)  << '\n';

   delete [] (&val);

   return 0;
}

But as you can see, this is not very readable and would be very prone to error. Best bet would be to just use std::vector.

Chad
  • 18,706
  • 4
  • 46
  • 63
0

No, but you can use dynamic types from std library, like std::vector.

The type std::vector acting very similar to array.

Look at this std::vector.

nrofis
  • 8,975
  • 14
  • 58
  • 113