Is it possible to get the pointer the continous memory fragment in a std::vector in C++?

后端 未结 3 1461
轻奢々
轻奢々 2021-01-19 16:16

I moved my code to use std::vector instead of char *mem = malloc(...) but now I am facing a problem that I can only access the vector d

相关标签:
3条回答
  • 2021-01-19 16:33

    The standard way to access the vector data is to use

    &data[0]
    
    0 讨论(0)
  • 2021-01-19 16:53

    You can write that code perfectly legally. All you need to do is alter fill_data to take a std::vector<T>&. Of course, if this is an external C API, then you don't have much choice in the matter.

    0 讨论(0)
  • 2021-01-19 16:57

    Of course. The vector was designed for this purpose:

    char * p = &(myVector[0]) ;
    

    And now, p points to the first item in the vector, and you can access each item by playing with the pointer, as you would in C.

    0 讨论(0)
提交回复
热议问题