Foo** 怎么是一个数组数组

How is Foo** an array of arrays?

本文关键字:数组 一个 Foo      更新时间:2023-10-16

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

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

它实际上不是一个数组数组。 但是,您可以使用与实际 2D 数组相同的语法访问各个元素。

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 FAQ 中有关此主题的所有部分:数组和指针(几乎所有数组和指针在 C++ 中都同样有效)。

但是,在C++中,通常很少有理由使用这样的原始指针。 您的大多数需求都可以通过容器类更好地处理,例如 std::vectorstd::arrayboost::multi_array

不是数组的数组,但您可以通过以下方式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;

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

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

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

相关文章: