简体   繁体   中英

dynamic array c++ without pointer

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];
}

Yes, of course, it is possible:

#include <iostream>
int main()
{
    [](int array[] = new int[10]) {
        std::cout << "array = " << array << "\n";
        delete[] array;
    }();
}

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.

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;

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 .

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM