[英]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
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.