gpt4 book ai didi

c++ - C++ 中的二维整数数组

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:46:09 25 4
gpt4 key购买 nike

我正在尝试在 C++ 中的堆上创建一个二维整数数组。我错误地这样做了:

int** a = new int*[5][6];

IDE 没有显示任何错误,但在编译时出现以下错误:

error: cannot convert 'int* (*)[6]' to 'int**' in initialization

我找到了创建二维数组的有效方法,但我只是好奇上面到底发生了什么,错误是什么意思?

最佳答案

C++ 中的固定大小数组拼写为 std::array:

std::array<std::array<int,5>,6> arr;

可变大小数组拼写为std::vector:

std::vector<std::vector<int>> arr;

你几乎不应该将 new 与其中任何一个一起使用(或与此相关的任何其他地方)。但如果你真的需要,没问题:

auto arr = new std::array<std::array<int,5>,6>;

这确实很少需要。更喜欢将数组包装在面向问题的类中,并使用智能指针管理所述类的堆分配对象。

关于c++ - C++ 中的二维整数数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38035250/

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