0

I have a function that return a vector of bytes (unsigned chars). How can I get that data into an array. Apparently the vector is contiguous virtual memory, so that should be easy. I have tried doing this

std::vector<unsigned char> a;
unsigned char* b = &a[0];

but I have not had any luck.

My code looks something like this

// 20 is length of returned vector
const int SOME_LENGTH = 20;
vector<unsigned char> a = get_some_bytes(SOME_LENGTH);
unsigned char b[SOME_LENGTH];
b = &a;

But I am getting this error

error: incompatible types in assignment of ‘std::vector<unsigned
char>*’ to ‘unsigned char [20]’
YSC
  • 38,212
  • 9
  • 96
  • 149
John Frye
  • 255
  • 6
  • 22
  • What the linked to answer proposes and what you did are as different as night and day. – StoryTeller - Unslander Monica Jan 09 '18 at 13:54
  • `unsigned char b[a.size()];` VLAs are a non-standard C++ extension. – Borgleader Jan 09 '18 at 13:55
  • @StoryTeller how? hes pointing the memory location of one double to the start of the vector. I want to point the memory location of the first of a contiguous set of unsigned chars to the first memory location in the vector – John Frye Jan 09 '18 at 13:58
  • 1
    Which is precisely what you are not doing. You don't declare a pointer, you declare an array (by extension). And the address of the vector is not the same thing as the address of the buffer it manages. – StoryTeller - Unslander Monica Jan 09 '18 at 13:59
  • @Borgleader you are saying since a.size() is not constant int, that allocation will not work? Either way, in my actual code, I have a constant int set to the number that goes into both the function and the buffer allocation. I will update my code – John Frye Jan 09 '18 at 14:01
  • 1
    Scrolling down to at least the second answer would have helped. :/ – Baum mit Augen Jan 09 '18 at 14:06
  • 1
    Also, it seems like you are lacking knowledge about some core concepts of C++. Reading a good C++ book sounds like a productive idea. – Baum mit Augen Jan 09 '18 at 14:08

2 Answers2

3

Simply copy bytes from the vector's data to your array:

std::copy(begin(a), end(a), b);

Note though you could directly use a.data()(no copy needed) in lieu of b almost everywhere.

YSC
  • 38,212
  • 9
  • 96
  • 149
0

You cant initialize array like that. You have to use pointers.

Here is a simple solution. If you know the size you can do this:

const size_t SIZE = 5000; // for example
unsigned char b[SIZE];
for(int i = 0; i < a.size(); i++)
    b[i] = a[i];

But if you don't know the size, then you have to use the new operator

unsigned char * b = new unsigned[a.size()];
for(int i = 0; i < a.size(); i++)
   b[i] = a[i];

Edit

In your case you can do this:

vector<unsigned char> a = get_some_bytes(SOME_LENGTH);
unsigned char * b = &a[0];
Petar Dimov
  • 301
  • 2
  • 11