Home >Backend Development >C++ >How to Obtain a Raw Data Pointer from a `std::vector`?
Providing a Raw Data Pointer for std::vector
When working with std::vector as a char array, there may be a need to pass a raw data pointer to a function that expects a void pointer. Originally, char arrays were used for this purpose, as exemplified by the code:
char something[] = "my data here"; process_data(something);
However, the dynamism of std::vector is desirable, leading to the following attempt:
vector<char> something; *cut* process_data(something);
The challenge arises in passing the char vector to the function such that it can access the vector's raw data.
Passing the Raw Data Pointer
Passing the address of the vector object, using &something, is incorrect as it does not provide the address of the data. Similarly, using &something.begin() is non-standard and results in a warning.
The correct approach is to obtain the address of the initial element of the container, which can be achieved via:
&something[0] // or &something.front() &*something.begin()
In C 11, the std::vector class introduces a new member function, data(), which serves the same purpose as the above methods. It returns the address of the initial element of the container and is safe to use even when the container is empty.
The above is the detailed content of How to Obtain a Raw Data Pointer from a `std::vector`?. For more information, please follow other related articles on the PHP Chinese website!