简体   繁体   中英

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";

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM