Home  >  Article  >  Backend Development  >  How to Retrieve a Raw Data Pointer from a std::vector?

How to Retrieve a Raw Data Pointer from a std::vector?

Barbara Streisand
Barbara StreisandOriginal
2024-11-11 17:34:02226browse

How to Retrieve a Raw Data Pointer from a std::vector?

Retrieving Raw Data Pointer from std::vector

Problem:

You seek to use a std::vector as a char array within a function accepting a void pointer. Attempts to pass the vector directly or through its begin() iterator have resulted in incorrect data or compiler warnings.

Solution:

To access the raw data of a std::vector, obtain the address of its initial element using one of the following methods:

  • &something[0] or &something.front() - returns the address of the element at index 0.
  • &*something.begin() - returns the address of the element pointed to by the begin() iterator.

In C 11 onwards, an additional option is available:

  • &something.data() - returns the address of the initial element, ensuring safety even for empty containers.

Examples:

void process_data(const void *data);

std::vector<char> something;

// Cast the raw data pointer to char* for compatibility.
char *data_ptr = reinterpret_cast<char*>(something.data());
process_data(data_ptr);

The above is the detailed content of How to Retrieve a Raw Data Pointer from a std::vector?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn