Richard Knop
Richard Knop

Reputation: 83677

How to convert char* to std::vector?

I have a char* variable:

// char* buffer;
// ...
fread (buffer, 1, lSize, pFile);
// ...

How can I convert it to std::vector? Casting will get me an error.

Upvotes: 35

Views: 74668

Answers (3)

mgiuca
mgiuca

Reputation: 21357

You can't cast between a char* and a vector; pointer casting causes the result to have the exact same bytes as the input, so it's generally a bad idea unless you're doing low-level bit manipulation.

Assuming you wanted to build a vector of chars, you can create a new vector object of type std::vector<char> (note that you need to supply the type of the vector's elements), and initialise it from the array by passing the begin and end pointers to the constructor:

std::vector<char> vec(buffer, buffer+lSize);

Note that the second argument is an "end pointer", very common in C++. Importantly, it is a pointer to the character after the end of the buffer, not the last character in the buffer. In other words, the start is inclusive but the end is exclusive.

Another possibility (since you're dealing with chars) is to use a std::string instead. This may or may not be what you want (depending on whether you're thinking about the char* as a string or an array of bytes). You can construct it in the same way:

std::string str(buffer, buffer+lSize);

or with a different constructor, taking the size as the second argument:

std::string str(buffer, lSize);

Upvotes: 14

ronag
ronag

Reputation: 51245

std::vector<char> data(buffer, buffer + size);

James McNellis answer is better if you can do it like that.

Upvotes: 106

James McNellis
James McNellis

Reputation: 354979

Why not use a std::vector to begin with:

std::vector<char> buffer(lSize);
std::fread(&buffer[0], 1, buffer.size(), pFile);

Upvotes: 20

Related Questions