Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to correctly use vector<uint8_t>.data()?

vector.data() should return a pointer to the first element, but when I use it on a vector<uint8_t>, it somhow returns somthing else:

int main() {
    std::string myString = {"a b c all the way long"};
    std::vector<uint8_t> myVec(myString.begin(), myString.end());
    std::cout << myVec.data() << std::endl;
    
    std::vector<int> anotherVec = {4,5,2,3}; 
    std::cout<< anotherVec.data() << std::endl;

    return 0; 
}

program prints:

a b c all the way long
0x124bf00

Why does the first print show all of the vector, and the second print shows the pointer? I was expecting both to print a pointer.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The real issue is that on another big program, when I print vector<uint8_t>.data() with cout, it prints garbage after it (when I look at it in the debugger, I don’t see the garbage).

>Solution :

The data() function returns a pointer to the first element.

myString is a vector of uint8_t values, so data() will return a value of type uint8_t*. uint8_t is a type based on char, so the << stream output operator will treat it as a null-terminated string. The problem here is that myVec doesn’t contain a null-terminated string, so this is technically undefined behavior.

For anotherVec, that’s a vector of int values, which means that data() returns a value of type int*, which has no specific overload for the << stream output operator. Instead, it uses the closest possible overload, which is the one to print generic pointers of type void*.

If you want the first to print the pointer itself, then you need to explicitly cast the pointer to void*:

std::cout << static_cast<void*>(myVec.data()) << '\n';
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading