将指针传递给指针数组

时间:2014-11-26 07:50:11

标签: c++ arrays pointers

我有一个测试函数,它将数组作为参数。我有一系列指针。有人可以解释为什么我传递它时需要将指针指向一个指针数组吗?

void test(States a[]){

    cout << a[0].name << endl;
    cout << a[1].name << endl;
}

致电test()

States *pStates[MAX_STATES];
test(*pStates); //Or test(pStates[0])
                //Can't do test(pStates);

3 个答案:

答案 0 :(得分:0)

如果测试函数的参数期望如此

,则不需要取消引用
void test(States *a[]);

但是在你的情况下,显然参数类型是States [],所以你需要传递一个指针。

您可能需要考虑将测试功能重写为:

void test(States *a[]){
    cout << a[0]->name << endl;
    cout << a[1]->name << endl;
}

答案 1 :(得分:0)

请改用:

void test(States* a[]){

    cout << a[0]->name << endl;
    cout << a[1]->name << endl;
}

你不需要取消引用它......

答案 2 :(得分:0)

pStates的声明声明了一系列指针。不是指向数组的指针。 但是函数void test(States a[]);需要一个对象数组(States个对象)。

你不能只把一个投射到另一个。

#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;
}

请参阅此处https://stackoverflow.com/help/mcve

相关问题