Search code examples
c++stdvectordereference

Dereference member pointer before operator[]


I can't seem to manage the syntax to access the elements of a vector, the pointer of which is contained in a structure. More after the MWE:

#include <vector>
#include <stdio.h>

typedef struct vectag
  {
    std::vector<float> *X;
  } vec;

int main ()
  {
    vec A;
    A.X = new std::vector<float>(0);

    A.X->push_back(5.0);

    // This next line is the problem:
    float C = A.X[0];

    printf("%f\n", C);
    return 1;
  }

GCC (G++) says

14:24: error: cannot convert ‘std::vector<float>’ to ‘float’ in initialization

and of course, it's quite right. In the line float C = A.X[0];, B.X[0] would be correct IF X was not a pointer (recall, std::vector<float> *X;). What is the proper syntax for dereferencing X before operator[], so that I can access the elements of X?

P.S. I am aware of the member function at(), and it is not an option for me because I don't want the overhead of range checking. This is part of a performance critical code.


Solution

  • A.X[0] attempts to access the first vector pointed to by X - which, remember, is a pointer.

    To use operator[] on the vector itself, you can use A.X->operator[](0), although quite honestly I don't see the reason why your member is a pointer and not an object.

    Your code exibits undefined behavior, because X is an unitialized pointer

    vec A;
    A.X->push_back(5.0);
    

    here.