[英]Passing pointer to an array of pointers
I have a test function that takes an array as an argument. 我有一个测试函数,将数组作为参数。 And I have an array of pointers. 而且我有一个指针数组。 Can someone explain why I need to deference the pointer to an array of pointers when I pass it? 有人可以解释为什么在传递指针时为什么需要将指针引用到指针数组吗?
void test(States a[]){
cout << a[0].name << endl;
cout << a[1].name << endl;
}
Calling test()
: 调用test()
:
States *pStates[MAX_STATES];
test(*pStates); //Or test(pStates[0])
//Can't do test(pStates);
You won't need to dereference if the arguments of test function expect so 如果测试函数的参数期望如此,则无需取消引用
void test(States *a[]);
But in your case, clearly the argument type is States []
, so you need to pass a pointer. 但是在您的情况下,参数类型显然是States []
,因此您需要传递一个指针。
You may want to consider rewriting test function as: 您可能需要考虑将测试功能重写为:
void test(States *a[]){
cout << a[0]->name << endl;
cout << a[1]->name << endl;
}
Use this instead: 使用此代替:
void test(States* a[]){
cout << a[0]->name << endl;
cout << a[1]->name << endl;
}
And you won't need to dereference it... 而且您无需取消引用...
The declaration of pStates
declares an array of pointers. pStates
声明声明了一个指针数组。 Not a pointer to an array. 不是指向数组的指针。 However the function void test(States a[]);
但是函数void test(States a[]);
expects an array of objects ( States
objects). 需要一个对象数组( States
对象)。
You can't just cast one to the other. 您不能只将其中一个投向另一个。
#include <iostream>
typedef struct {
int name;
} States; //Surely this should be called State (not plural)
const size_t MAX_STATES=2;
void test(States a[]){
std::cout << a[0].name << std::endl;
std::cout << a[1].name << std::endl;
}
int main() {
States lFirst;
States lSecond;
lFirst.name=1;
lSecond.name=7;
//Here's what you had.
States*pStates[MAX_STATES];
//Now initialise it to point to some valid objects.
pStates[0]=&lFirst;
pStates[1]=&lSecond;
//Here's what you need to do.
States lTempStates[]={*pStates[0],*pStates[1]};
test(lTempStates);
return EXIT_SUCCESS;
}
Please see here https://stackoverflow.com/help/mcve 请在这里查看https://stackoverflow.com/help/mcve
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.