Search code examples
c++arraysvectorpvm

Can I cast std::vector<int>* to int*?


Let's say I have a std::vector<int>* foo; and I have to use it as int* (array of int, not pointer to an int) for an old C type library PVM. As far as I am concerned this might work since the vector stores it's elements next to each other in memory just like arrays. So I tried (int*)foo, but somehow I get an error which I'm unable to debug, so I think this must be the problem. Any ideas, thoughts, elegant workarounds?


Solution

  • You can't cast the vector directly to an array because the vector object consists of pointers to the array data, not the array data itself, which is dynamically allocated. To access the underlying array, use the data() member function:

    std::vector<int> vec;
    
    int *arr = vec.data();
    

    Or

    std::vector<int> *vecp = new std::vector<int>;
    
    int *arr = vecp->data();