'Pointer to single bytes of vector of doubles
I have vector of doubles and I need to have pointer with access to each single byte (probably char *ptr). Can you tell me how to assign pointer to char to vector, so I can read values of each byte?
C++
Solution 1:[1]
std::vector<T> has a method: T * data(),
which returns a pointer to the vector's data.
In a vector of doubles, data() will return a double*.
You can then use reinterpret_cast to cast the pointer to a single byte pointer (e.g. unsigned char pointer).
std::vector<double> a;
double * pData = a.data();
unsigned char * pDataBytes = reinterpret_cast<unsigned char*>(pData);
However - you should know exactly what you are doing. Using reinterpret_cast can cause many problems and UB.
UPDATE:
Based on the comments, I would like to correct that using reinterpret_cast<unsigned char*> by itself is not UB. I just meant that once you start to mess with the byte representation of objects which have other kinds of content, you have to know exactly what you are doing, as it is easy to do things that lead to UB.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
