将std :: vector <t>转换为char *

时间:2017-05-13 09:48:02

标签: c++

我正在尝试将vector转换为char *,以便通过套接字发送 T的类型是一个简单的结构

struct CategoryStruct {
    int ID;
    char name[32];
};

std::vector<CategoryStruct> categories;

功能,我正在尝试转换 -

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

结束回报将是“”

1 个答案:

答案 0 :(得分:2)

不需要转换std::vector<CategoryStruct>已将数据存储在一个有争议的内存区域。所以你的功能可以归结为

std::vector<CategoryStruct> categories;
char * Category::decodeCategoryToCharArray()
{
    return reinterpret_cast<char*>(categories.data());
}