簡體   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