c++ - 填充 Char 指针的结构

标签 c++

假设您有这样的结构:

struct MMFS_IDENTIFICATION
{
    char *szVendor;
    char *szControllerModel;
    char *szRevision;
    char *szId;
    char *szExecutive;
    char *szKarelRevision;
    char *szProcessName;
    char *szCommRevision;
    char *szRobotModel;
};

有什么简单的方法可以做这样的事情吗?

MMFS_IDENTIFICATION mmfsId;

for( int i = 0; i < 9; i++ )
{
    int len = buf[pos++];
    mmfsId[i] = malloc(len);
    memcpy( mmfsId[i], buf[pos], len );
    pos += len;
}

我唯一知道的就是将代码复制粘贴九次。但我真的不想这样做,因为在我使用这个概念的实际程序中,计算 len 并不像我在这个例子中做的那么简单。

最佳答案

由于您的结构包含 9 个具有不同名称的不同指针,因此访问它们的唯一标准方法是使用 9 段不同的代码。您可能会尝试作弊并依赖结构的内部表示,甚至可能会侥幸逃脱,但不建议这样做。

使用一个函数将每一 block 变成一个单行。

void CopyString(char * & string_ptr, char * buf, int & pos)
{
    int len = buf[pos++];
    string_ptr = new char[len];
    memcpy( string_ptr, buf[pos], len );
    pos += len;
}

CopyString(mmfsId.szVendor, buf, pos);
CopyString(mmfsId.szControllerModel, buf, pos);
CopyString(mmfsId.szRevision, buf, pos);
CopyString(mmfsId.szId, buf, pos);
CopyString(mmfsId.szExecutive, buf, pos);
CopyString(mmfsId.szKarelRevision, buf, pos);
CopyString(mmfsId.szProcessName, buf, pos);
CopyString(mmfsId.szCommRevision, buf, pos);
CopyString(mmfsId.szRobotModel, buf, pos);

关于c++ - 填充 Char 指针的结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8084829/

相关文章:

c++ - C/C++ 中的 for 循环变量优化

c++ - OpenCV 的 cvWaitKey() 函数有什么作用?

c++ - GLX 上下文帧缓冲区读取

c# - CreateCompatibleDC(IntPtr.Zero) 返回 IntPtr.Zero

python - 让 Valgrind 检测 Python 脚本 : 调用的 C++ 程序的内存泄漏

c++ - C++ 库的 C 包装器,iostream 和 gcc 的问题

c++ - 无法创建动态文件夹名称

c++ - 正在检查大型订购 list 中的成员资格?

c++ - 如何将格式字符串发送到 iostream?

c++ - utf-8 中 std::string 的子字符串? C++11