指向指针 C++ 的指针

Pointer to pointer C++

我真的不能理解 C++ 中指向指针的指针是什么。假设我有一个 class 定义如下:

class Vector3 
{
   public:
         float x,y,z;
         //some constructors and methods
}

现在如果我有类似

的东西怎么办
Vector3 **myVector3;

这在 C# 中是否等同于说 List<List<Vector3> myVector3? 无论如何,我如何动态分配这个 myVector3 对象? 谢谢

你可以这样做:

Vector3 * pointer = new Vector3; // points to a instance of Vector3 on the heap
Vector3 * * pointerToPointer = & pointer; // points to pointer; we take the address of pointer
Vector3 **myVector3;

基本上只是一个指向另一个指针的指针。取消引用它会给你一个指向 Vector3.

的指针

示例:

#include <iostream>

class Vector3
{
public:
    float x, y, z;
    //some constructors and methods
};

int main()
{
    Vector3 **myVector3 = new Vector3*[50]; // allocate 50 Vector3 pointers and set myVector3 to the first, these are only pointers, pointing to nothing.
    //myVector3[0]->x; myVector3[0] is a Vector3 pointer, currently pointing to nothing dereferencing this will result in Undefined Behaviour
    myVector3[0] = new Vector3; // allocate a Vector3 on the heap and let pointer 1 ( of the 50 ) point to this newly allocated object.
    myVector3[0]->x = 5;
    std::cout << "myVector3[0]->x : " << myVector3[0]->x; // prints "myVector3[0]->x : 5"
    std::cin.get();
}

List 的 C++ 等价物是 std::vector。不要介意你的 class 被称为向量;这是一个向量,就像在动态可扩展的同类对象序列中一样。

如果你想要一个 C++ 中 Vector3 列表的列表,你想要

std::vector<std::vector<Vector3> myVectorVectorVictor;

那也分配了一个。不需要指点。

Is this SOMEHOW the C#'s equivalent of saying List<List<Vector3> myVector3?

没有

And anyway, how can I dynamically allocate this myVector3 object?

我不明白这个问题。

I can't really understand what pointer to pointer is in C++.

回到第一校长。什么是变量?对于特定类型.

,变量是存储

可以对变量进行哪些操作?它们可能读取,写入,或者它们的地址可能被占用.

地址获取运算符 & 的结果是什么?指向变量的指针。

什么是指针? 表示变量

指针值可以进行哪些操作?使用 * 可以 取消引用 指针。这样做会产生一个 变量 。 (指针上还有其他可用的操作,但我们不用担心这些。)

所以让我们总结一下。

Foo foo;Foo 类型的变量。它可以包含 Foo.

&foo 是一个指针。这是一个价值。取消引用时,它会生成变量 foo:

Foo foo;
Foo *pfoo = &foo;
*pfoo = whatever; // same as foo = whatever

pfoo 是一个变量。一个变量可能有它的地址:

Foo **ppfoo = &pfoo;
*ppfoo = null;  // Same as pfoo = null.  Not the same as foo = null.

好了。 ppfoo 是一个变量。它包含一个值。它的值是一个指针。当该指针被取消引用时,它会产生一个变量。该变量包含一个值。该值是一个指针。当它被取消引用时,它会产生一个变量。该变量的类型为 Foo.

确保您对此非常清楚。当你感到困惑时,回到第一原则。指针是值,它们可以被取消引用,这样做会产生一个变量。一切都源于此。