0

I have a std::vector<uint8_t[1115]> and I want to store a char* in it. I don't understand how I have to cast the char* to fit it into the vector. Maybe its stupid but I tried this:

char* myCharArray = new char[1115]; 
std::vector<uint8_t[1115]> myVector;
myVector.push_back(reinterpret_cast<uint8_t*>(myCharArray));

I don't understand why this is not working. The error is as follows:

error: no matching function for call to ‘std::vector<unsigned char [1115]>::push_back(uint8_t*)’ 
telina
  • 166
  • 1
  • 1
  • 11
  • Also clarify what "not working" means. Does it not compile, or crash, or cause weird output, or steal your Facebook friends? – molbdnilo Jan 16 '15 at 10:24
  • error: no matching function for call to ‘std::vector::push_back(uint8_t*)’ – telina Jan 16 '15 at 10:27
  • 1
    You had actually given the appropriate information but it wasn't showing because you hadn't formatted your question correctly. Please place back-ticks around any inline code in the future. – Joseph Mansfield Jan 16 '15 at 10:29

1 Answers1

2

You have two issues:

  1. A vector's elements have to be copy constructible and assignable, but an array is not. That means that you can't legally have a vector of arrays. If you are using C++11 or later, you can use a std::vector<std::array<uint8_t, 1115>>. The std::array type is a copyable wrapper around an array.

  2. push_back takes an object that it can insert into the vector simply by copying the object. You can't copy a char* (or any other point) to an array. However, if you follow my recommendation in (1), you can avoid the pointer entirely, and just make it std::array<uint8_t, 1115> myCharArray;.

If std::array is not available to you, you could use a std::vector<std::vector<uint8_t>> and just make sure the inner vectors are the right size.

You might be interesting in looking at why you probably won't need raw pointers or new in most of your C++.

Community
  • 1
  • 1
Joseph Mansfield
  • 108,238
  • 20
  • 242
  • 324