在 C 中,我做
int (*ptr)[100];
ptr=malloc(sizeof *ptr); // this is the easy/error proof way of doing it
是否有一种 C++ 方法可以用 new
运算符做同样的事情
int (*ptr)[100];
ptr=new __what_comes_here?
最佳答案
int (*ptr)[100];
表示 ptr
是一个指针,它应该保存一个包含 100 个整数的数组的地址。换句话说,从技术上讲,如果你有,比如:
int arr[100]; // automatic (compile time allocated) object of 100 integers
那么你可能想使用:
ptr = &arr;
但是这里不是这样的。所以你可以用一个简单的指针来做。如果你想动态化,那么你要么选择 malloc
等价物:
int *p = new int[100]; // do `delete[] p` later to reclaim memory
请注意,p
是一个简单的指针,它保存着动态分配数组的第一个整数的地址。
但更好的做法是使用标准容器来避免任何内存管理:
std::vector<int> v(100);
如果尺寸 100 是固定的,那么您可以使用:
int a[100]; // C-style
或者
std::array<int, 100> arr; // C++11 onwards
如果您需要 new
并且没有使用上述功能的奢侈但仍然希望自动回收内存,那么使用 unique_ptr
作为 following :
std::unique_ptr<int[]> p(new int[100]);
关于c++ - 将新运算符应用于数组指针的防错方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38691438/