gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 01:17:54 26 4
gpt4 key购买 nike

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

用下面的代码

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

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

问题 1:

如果我希望每个元素都是指向固定数组大小的指针,如何声明 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

问题 2:

根据我上面的原始代码示例,除了调用 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com