简体   繁体   English

没有指针的动态数组c ++

[英]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)? 是否可以在不使用显式指针的情况下在c ++中创建动态数组(int array []而不是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. 编译器需要知道数组的大小,因此要在c ++中使用堆栈分配的数组,必须在声明中指定它。 I recommend you look at the STL Vector class instead. 我建议你改为查看STL Vector类。

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> . 您可以将指针隐藏在类似std::vector<int>

You could do something like 你可以做点什么

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

to delete: delete [] array; 删除: 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 . 最好的选择是使用std::vector

No, but you can use dynamic types from std library, like std::vector . 不,但你可以使用std库中的动态类型,比如std::vector

The type std::vector acting very similar to array. 类型std::vector作用与数组非常相似。

Look at this std::vector . 看看这个std :: vector

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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