创建指针对象指针的正确方法?

dom*_*lao 0 c++

创建指针对象指针的正确方法是什么?例如,

int **foo;
foo = new int[4][4];
Run Code Online (Sandbox Code Playgroud)

然后编译器给我一个错误,说"无法从int(*)[4]转换为int**.

谢谢.

Fil*_*ara 10

int **foo = new int*[4];
for (int i = 0; i < 4; i++)
   foo[i] = new int[4];
Run Code Online (Sandbox Code Playgroud)

澄清:

在许多语言中,上面的代码称为锯齿状数组,它仅在"行"具有不同大小时才有用.C++对动态分配的矩形数组没有直接的语言支持,但它很容易自己编写:

int *foo = new int[width * height];
foo[y * height + x] = value;
Run Code Online (Sandbox Code Playgroud)


Joh*_*itb 8

使用raw new有点难以使用.另外,内部维度(最后4个)必须是编译时常量.完成使用后,您还必须记住删除该数组.

int (*foo)[4] = new int[4][4];
foo[2][3] = ...;
delete[] foo;
Run Code Online (Sandbox Code Playgroud)

如果这感觉太"语法脑de",你可以使用typedef来美化它

typedef int inner_array[4];
inner_array *foo = new int[4][4];
foo[2][3] = ...;
delete[] foo;
Run Code Online (Sandbox Code Playgroud)

这被称为矩形二维数组,因为所有行(其中4个,可以在运行时确定)具有相同的宽度(必须在编译时知道).

或者,使用std::vector,您不再需要删除删除,并且还将处理原始指针混乱:

std::vector<int> v(4 * 4);
v[index] = ...;
Run Code Online (Sandbox Code Playgroud)

您可以根据需要在矢量中添加或删除整数.您也可以创建一个vector< vector<int> >,但我发现它使用起来不实用,因为您必须管理单独的行向量(可以是不同长度),并且它们不会被视为"一个单元".

您始终可以创建将二维坐标映射到一维索引的函数

inline int two_dim(int x, int y) {
  return y * 4 + x;
}

v[two_dim(2, 3)] = ...;
Run Code Online (Sandbox Code Playgroud)

对于一个简单的二维数组的大小,你事先知道,你并不需要new在所有的,虽然

int x[4][4]; 
x[2][3] = ...;
Run Code Online (Sandbox Code Playgroud)