Reputation: 210
My aim is to set vec
array to intData
array. I read this question and applied it to my code. I resized intData before doing the process. In C# this intData = GetIntArrayFromByteArray(vec);
creates no problem but I am confused when it comes to array vectors in C++. I stated where I get the error as a comment. I tried resizing but it didn't work. Can someone help me please?
Code explanation;
buf
gets a message(it is not empty I get message from client)
I create a vector array vec
same size as buf
GetIntArrayFromCharArray()
converts char vector array into int array
vector.
char buf[1550];//message gets here not empty
vector<uint16_t> intData; //empty int vector
//char buf ----> vecor<char> vec
int n = sizeof(buf) / sizeof(buf[0]);
vector<char> vec(buf, buf + n);
intData.resize(vec.size());//here I resize
/*
irrelevant code piece runs here
*/
if (something == 1)// First fragment
{
intData = GetIntArrayFromCharArray(vec);//size out of range error here
}
This is GetIntArrayFromCharArray()
does the conversion
vector<uint16_t> GetIntArrayFromCharArray(vector<char> arr)
{
// If the number of bytes is not even, put a zero at the end
if ((arr.size() % 2) == 1)
arr.resize(arr.size()+1);
arr.push_back(0);
vector<uint16_t> intArray;
for (int i = 0; i < arr.size(); i += 2)
intArray.push_back((uint16_t)((arr[i] << 8) | arr[i + 1]));
return intArray;
}
Upvotes: 0
Views: 65
Reputation: 385295
// If the number of bytes is not even, put a zero at the end
if ((arr.size() % 2) == 1)
arr.resize(arr.size()+1);
arr.push_back(0);
Whoops!
This is actually:
The consequence is that you will always have an odd number of elements. This breaks the subsequent loop as you try to read one past the end of the vector.
I don't think you meant to put that push_back
there, or perhaps you meant to have it instead of the resize
call.
By the way, as Jarod pointed out, resizing intData
up-front is a complete waste of time since the next thing you do with it (as far as we can see) is to replace the whole vector.
Upvotes: 2