I'm trying convert vector to char * for send by socket the type of T is a simple struct
struct CategoryStruct {
int ID;
char name[32];
};
std::vector<CategoryStruct> categories;
Function, where I'm trying to convert -
char * Category::decodeCategoryToCharArray()
{
int structSize = sizeof(CategoryStruct),
currentByte = 0,
i = 0;
if(decoded)
delete [] decoded;
decoded = new char[structSize * categories.size()];
std::vector<CategoryStruct>::iterator start, end;
start = categories.begin();
end = categories.end();
for(; start != end; start++, i++)
{
memcpy(decoded+currentByte, &categories[i], structSize);
currentByte += structSize+1;
}
return decoded;
}
End return will be ""
There's no need for conversion , std::vector<CategoryStruct>
already stores the data in a contigous memory area. so your function could be boiled down to
std::vector<CategoryStruct> categories;
char * Category::decodeCategoryToCharArray()
{
return reinterpret_cast<char*>(categories.data());
}
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.