通过在C++中作为指向函数的指针传递来访问std :: array元素的正确方法是什么?

bla*_*nky 1 c++ c++14

代码段如下.错误在cout行的foo函数中:

typedef struct Datatype {
    int first;
    int second;
} Datatype;

void foo(std::array<Datatype, 100>* integerarray){
    cout << *integerarray[0].first << endl; //ERROR: has no member first
}

void main() {
    std::array<Datatype, 100> newarray;
    for(int i=0; i<100; i++)
        newarray[i] = i;
    }
    foo(&newarray);
}
Run Code Online (Sandbox Code Playgroud)

R S*_*ahu 9

由于运算符优先级,*integerarray[0].first被翻译为*(integerarray[0].first),这不是你想要的.你需要使用(*integerarray)[0].first.

cout << (*integerarray)[0].first << endl;
Run Code Online (Sandbox Code Playgroud)

您可以通过传递参考来简化您的生活.

void foo(std::array<Datatype, 100>& integerarray){
  cout << integerarray[0].first << endl;
}
Run Code Online (Sandbox Code Playgroud)

此外,您不需要typedef struct DataType { ... } DataType;在C++中使用.你可以使用struct DataType { ... };