1

在 C++ 中,有人告诉我这Foo** foo;是一个指向指针的指针,也是一个数组数组?

有人会详细说明为什么它是数组数组或如何解释它?

4

4 回答 4

5

它不是真正的数组数组。但是,您可以使用与实际二维数组相同的语法访问各个元素。

int x[5][7];   // A real 2D array

// Dynamically-allocated memory, accessed through pointer to pointer
// (remember that all of this needs to be deallocated with symmetric delete[] at some point)
int **y = new int*[5];
for (int i = 0; i < 7; i++) {
    y[i] = new int[7];
}

// Both can be accessed with the same syntax
x[3][4] = 42;
y[3][4] = 42;

// But they're not identical.  For example:

void my_function(int **p) { /* ... blah ... */ }

my_function(x);  // Compiler error!
my_function(y);  // Fine

还有很多其他的微妙之处。要进行更深入的讨论,我强烈建议通读 C 常见问题解答中有关此主题的所有部分:数组和指针(几乎所有内容在 C++ 中同样有效)。

然而,在 C++ 中,通常很少有理由使用这样的原始指针。使用容器类(例如std::vectorstd::array或)可以更好地处理您的大部分需求boost::multi_array

于 2012-06-18T19:23:57.400 回答
2

它不是数组数组,但您可以Foo**通过以下方式构造数组数组:

Foo** arr = new Foo*[height];
for (int i = 0; i < height; ++i)
    arr[i] = new Foo[width]; // in case of Foo has default constructor

要访问单个元素,您可以使用

arr[i][j].some_method();

它也可以只是指向类型指针的指针Foo

Foo* fooPointer = &fooInstance;
Foo** fooPointerPointer = &fooPointer;
于 2012-06-18T19:25:25.257 回答
1

它不是数组的数组——指针不是数组,因此指向指针的指针不是指向数组的数组。

它们可以被类似地索引以存储和检索信息......因此在功能上它们的行为很像数组。

于 2012-06-18T19:26:37.047 回答
0

简单的回答:在 C++ 中,(可变大小,即没有像 int[5] 这样的固定大小)数组只是指向该数组第一个元素的指针。因此,编译器无法区分指针是指向数组的开头还是指向单个实例。因此,编译器始终允许您将指针视为数组。但是,如果指针没有指向足够大的内存块以用作数组,那么使用它会导致某种内存故障(分段故障或静默故障)。

于 2012-06-18T19:28:08.350 回答