Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::vector<uchar> to char* data loss

I used cv::imencode to encode a cv::Mat as image/jpeg into a vector<uchar> now I want to convert that vector to type char *.

vector<uchar> buf;

// print buf to stdout to ensure that data is valid here
for (auto c : buf)
    cout << c << endl;

// cast vector to char
char *ch = reinterpret_cast<char*>(buf.data());

// print out value of char pointer
for(int i = 0; ch[i] != '\0'; i++)
    printf("log: %c\n", ch[i]);

The for loop over the vector is taken from this question. The cast from std::vector<T> to char * is taken from this question.

The problem is now that there seems to be some data loss during the type conversion. Whereas buf contains valid data I always only get the value ???? printed from ch.

Any ideas what happened here?

like image 865
bodokaiser Avatar asked Nov 28 '25 23:11

bodokaiser


1 Answers

When you work with a vector, all is fine since à vector is a dynamic array with an explicit size. So it can contain null values.

But next, you use a null terminated unsigned character array. So it stops at first null character. It is even explicit in your code.

for(int i = 0; ch[i] != '\0'; i++)
    printf("log: %c\n", ch[i]);

(the relevant part being ch[i] != 0)

That's why you loose everything after first null character.

like image 146
Serge Ballesta Avatar answered Nov 30 '25 13:11

Serge Ballesta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!