c++ - 将新运算符应用于数组指针的防错方法

标签 c++ arrays pointers new-operator dynamic-allocation

在 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/

相关文章:

c++ - C++ 结构中指针的默认值

c++ - 如何修复由于 C++ includePath 导致的 "No such file or directory..."错误

c++ - 使库函数使用从库类派生的类

php - 推送到数组的特定位置

python - 使用 Numpy 进行矩阵运算的更简单方法

javascript - 将一维数组转换为多维数组

pointers - uint8_t* 与 uint8_t 之间的区别

c - 指针之间的赋值仅在 main 内部有效,而在过程体中无效

c++ - 如何找出 C++ header 在 Visual Studio 中编译需要多少时间?

c - 指针数组的初始化