Search code examples
c++pointersvectorstructdereference

Error trying to access a struct type using a pointer to a vector of structs


#include <iostream>
#include <vector>
using namespace std;

struct a_struct { int an_int; };

int main () 
{
    vector <vector <a_struct> > the_vec;
    vector <a_struct> * p_vs;
    p_vs = & the_vec[0];
    *(p_vs)[0].an_int=0;   //error: 'class __gnu_debug_def::vector<a_struct,
                           //std::allocator<a_struct> >' has no member named 'an_int'
}

I can't figure out why I'm getting the above compile error.


Solution

  • In C++, [] and . have higher precedence than *.

    Your last line

    *(p_vs)[0].an_int=0; 
    

    when fully parenthesized, is

    *((p_vs[0]).an_int)=0; 
    

    Since p_vs was declared as

    vector <a_struct> * p_vs;
    

    it is as if p_vs is an array of vector <a_struct> elements, so p_vs[0] is a vector<a_struct>.

    And vector<a_struct> objects indeed do not have a member an_int.

    Add some parens and you will get what you want.