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];
}
5
  • 11
    Why not std::vector? Commented Oct 11, 2012 at 21:01
  • You're probably aware of it, but could you not use std::vector for this purpose? Commented Oct 11, 2012 at 21:01
  • Related - Variable length arrays in C++? Commented Oct 11, 2012 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. Commented Oct 11, 2012 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? Commented Oct 11, 2012 at 21:06

5 Answers 5

2

Yes, of course, it is possible:

#include <iostream>
int main()
{
    [](int array[] = new int[10]) {
        std::cout << "array = " << array << "\n";
        delete[] array;
    }();
}
Sign up to request clarification or add additional context in comments.

2 Comments

Well, yes - but it is using the required notation! ;)
This might do what OP asked, but it's kludgey. Seriously, just use a vector.
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.

Comments

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.

Comments

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.

Comments

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;

2 Comments

That's terrifying. Also will leak unless deleted in a similar manner.
To delete it you just need the address of the first element, and to get that you can rely on the automatic conversion for arrays.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.