regexfun
regexfun

Reputation: 21

How can you copy a vector to vector with pointers in C++

I can't seem to find a good answer to this but I am currently trying to copy the first 10 values of a vector into another vector but it is a char*. Here is my current relevant code:

vector<char> letters {.... many letters}
vector<char*> evenMoreLetters;
evenMoreLetters.reserve(5)

for(int i = 0; i < 10; ++i)
{
    evenMoreLetters.push_back(&letters[i]);
}

//Code used to output evenMoreLetters
for(int i= 0; i < evenMoreLetters.size(); i++)
{
  std::cout << evenMoreLetters[i];
}
cout << "\n";

Upvotes: 1

Views: 126

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 595672

operator<< has an overload for char*, but it requires the char* to be a pointer to a null-terminated string. Your char* pointers are not pointing at null-terminated strings, hence the random garbage you are seeing. Your code has undefined behavior from reading into surrounding memory.

If you want to print out the single characters being pointed at, you need to dereference the pointers so you call the operator<< overload for char instead, eg:

std::cout << *(evenMoreLetters[i]);

Otherwise, use cout.write() instead:

std::cout.write(evenMoreLetters[i], 1);

Upvotes: 3

Related Questions