我对指针使用的基础知识有两个疑问。
使用以下代码
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 calldelete[]
while I cannot find an expression where I can call only simply delete.
我完全不明白为什么这是一个问题,但是你可以通过将数组包装在另一种类型中来做到这一点......比如 std::array
, boost::array
或 std::vector
。
关于c++ - 分配指向固定大小数组的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7719905/