繁体   English   中英

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

[英]dynamic array c++ without pointer

是否可以在不使用显式指针的情况下在c ++中创建动态数组(int array []而不是int * array)?

即。 这样的事情:

int size = 5;
int array[];

array = new int{size};

for (int i = 0; i < size; i++)
{
    array[i];
}

是的,当然,有可能:

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

简而言之,没有。 编译器需要知道数组的大小,因此要在c ++中使用堆栈分配的数组,必须在声明中指定它。 我建议你改为查看STL Vector类。

int array[]; 必须具有自动存储持续时间(在功能或类范围内)并且不能具有动态存储持续时间。

您可以将指针隐藏在类似std::vector<int>

你可以做点什么

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

删除: delete [] array;

您可以使用参考

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

但正如您所看到的,这不是非常易读,并且容易出错。 最好的选择是使用std::vector

不,但你可以使用std库中的动态类型,比如std::vector

类型std::vector作用与数组非常相似。

看看这个std :: vector

暂无
暂无

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

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