[英]How do I initialize a pointer to an array of pointers?
I am trying to initialize a pointer to an array of pointers.我正在尝试初始化一个指向指针数组的指针。 Here's an example:
下面是一个例子:
class MyClass { };
// INTENT: define a pointer to an array of pointers to MyClass objects
MyClass* (*myPointer)[];
int main(void) {
// INTENT: define and initialize an array of pointers to MyClass objects
MyClass * tempArray [] = {
new MyClass(),
new MyClass()
};
// INTENT: make myPointer point to the array just created
myPointer = tempArray;
}
When I compile this I get:当我编译这个时,我得到:
./test2.cpp: In function ‘int main()’:
./test2.cpp:15:19: error: cannot convert ‘MyClass* [2]’ to ‘MyClass* (*)[]’ in assignment
myPointer = tempArray;
^~~~~~~~~
First, arrays are not pointers.首先,数组不是指针。 You have to use the address-of:
您必须使用以下地址:
myPointer = &tempArray;
Next, when you write接下来,当你写
T foo[] = { t1, t2 };
this is just short-hand notation for这只是简写
T foo[2] = { t1, t2 };
Either use the correct type ( Live Example ):要么使用正确的类型(实时示例):
MyClass* (*myPointer)[2];
or perhaps better use a std::array<MyClass>
in the first place.或者最好首先使用
std::array<MyClass>
。 And forget about raw owning pointers.忘记原始拥有指针。 Use smart pointers instead.
改用智能指针。
// INTENT: define a pointer to an array of pointers to MyClass objects
MyClass* (*myPointer)[];
You can't obmit the size of the array in declaration.您不能在声明中省略数组的大小。 You need this:
你需要这个:
MyClass* (*myPointer)[2];
Then,然后,
MyClass * tempArray [] = {
new MyClass(),
new MyClass()
};
// INTENT: make myPointer point to the array just created
myPointer = &tempArray;
An array decays into a pointer to the first element.数组衰减为指向第一个元素的指针。 Since the element type is also a pointer, you can declare a variable that is a double-pointer and have it point at that element, eg:
由于元素类型也是一个指针,你可以声明一个双指针变量并让它指向那个元素,例如:
class MyClass { };
MyClass** myPointer;
int main(void) {
MyClass * tempArray [] = {
new MyClass(),
new MyClass()
};
myPointer = tempArray;
// same as:
// myPointer = &tempArray[0];
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.