假设您有这样的结构:
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/