c++ - 分配指向固定大小数组的指针

标签 c++ pointers multidimensional-array new-operator

我对指针使用的基础知识有两个疑问。

使用以下代码

 int (*p_b)[10];
 p_b = new int[3][10];
 // ..do my stuff
 delete [] p_b

p_b 指向一个包含 3 个元素的数组,每个元素的固定大小长度为 10 int。

第一季度:

如果我希望每个元素都是指向固定数组大小的指针,如何声明 p_b? 基本上我想要以下内容

  p_b[0] = pointer to a fixed-array size of 10
  p_b[1] = pointer to a fixed-array size of 10
  // ... and so on

我本来想int (** p_b)[10]但后来我不知道如何使用new来分配它?我想避免回到更通用的 int** p_b

第二季度:

根据上面我的原始代码示例,除了调用 p_b = new int[1][10] 之外,如何调用 new 以便 p_b 指向 10 int 的唯一固定大小数组?为了释放内存,我必须调用 delete[],但我找不到只能简单调用 delete 的表达式。

最佳答案

p_b is pointing to an array of 3 elements, each having fixed-size length of 10 int.

How to declare p_b if I want that each element be a pointer to a fixed array size?

你的第一句话没有完全涵盖这个问题吗?

Is per my original code sample above, how to call new so that p_b points to a unique fixed-size array of 10 int other than calling p_b = new int[1][10]? To free memory I have to call delete[] while I cannot find an expression where I can call only simply delete.

我完全不明白为什么这是一个问题,但是你可以通过将数组包装在另一种类型中来做到这一点......比如 std::array, boost::arraystd::vector

关于c++ - 分配指向固定大小数组的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7719905/

相关文章:

c++ - 如何使用vc++代码获取系统唯一ID?

c - 分配一个指向整数的指针

php - 如何递归地从多维数组中的每个值中删除周围的空格

java - 在二维数组中查找相邻元素并计算它们。

c++ - std::result_of 不编译

c++ - 在 Visual Studio 2013 中构建 OpenSSL

c++ - 是否有一个快速的内存队列我可以使用它在达到一定大小时交换项目?

c++ - 测试指针是否为空的最有效方法是什么?

c - 为什么 valgrind 提示单个链表节点删除时大小为 8 的无效读取?

c++ - 指向动态分配的 boost multi_array 中的类的指针,而不是编译