c++ 将指针传递给指针数组

b4lqfgs4  于 11个月前  发布在  其他
关注(0)|答案(3)|浏览(82)

我有一个测试函数,它接受一个数组作为参数。我有一个指针数组。有人能解释一下,为什么我需要在传递指针时将指针转换为指针数组吗?

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);

b1zrtrql

b1zrtrql1#

如果测试函数的参数期望如此,则不需要解引用

void test(States *a[]);

字符串
但是在你的例子中,很明显参数类型是States [],所以你需要传递一个指针。
您可能需要考虑将测试函数重写为:

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

hpxqektj

hpxqektj2#

用这个代替:

void test(States* a[]){

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

字符串
你不需要去引用它...

nnsrf1az

nnsrf1az3#

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

字符串

相关问题