将指针分配给固定大小的数组 [英] allocation of a pointers to fixed size arrays

查看:84
本文介绍了将指针分配给固定大小的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于指针使用的基本知识,我有两个疑问.

I have 2 doubts regarding basics of pointers usage.

使用以下代码

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

p_b指向一个由3个元素组成的数组,每个元素的大小固定为10 int.

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

第一季度:

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

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

  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

I was thinking to int (** p_b)[10] but then I don't know how to use new to allocate it? I would like to avoid falling back to more general int** p_b

第二季度:

按照上面的原始代码示例,如何调用new,以便p_b指向唯一的固定大小的10 int数组,而不是调用p_b = new int[1][10] ?为了释放内存,我必须调用delete[],而我找不到只能仅调用delete的表达式.

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.

推荐答案

p_b指向一个由3个元素组成的数组,每个元素的固定大小长度为10 int.

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

如果我希望每个元素都是一个指向固定数组大小的指针,该如何声明p_b?

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

您的第一句话不能完全解决这个问题吗?

Does your first sentence not completely cover that question?

按照上面的原始代码示例,如何调用new,以便p_b指向唯一的固定大小的10 int固定数组,而不是调用p_b = new int[1][10]?为了释放内存,我必须调用delete[],而我找不到只能调用delete的表达式.

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::arrayboost::arraystd::vector.

I completely do not understand why this is a problem, but you could do it by wrapping your array inside another type... say std::array, boost::array or std::vector.

这篇关于将指针分配给固定大小的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆