【发布时间】:2014-12-11 17:20:53
【问题描述】:
我想按照以下方法转换我的 STRUCT:
- 将 STRUCT 转换为字符数组。
- 将 char 表转换为 int 数组。
- 将 int 数组转换为 char 数组。
- 将 char 数组转换为 STRUCT。
但我在运行时有那些错误:
这是我的代码:
void rServer::convertStruct_to_char ( PCryptDATA p) {
// ***********convert struct to Array of char ************
char* frame= new char[p.size];
cout << p.size <<endl;
cout << endl;
memcpy(frame, &p, sizeof(p));
//***********convert Array of char to array of int ************
int taille= p.size;
int* out = new int[taille];
for (int i=0; i<taille+1;i++)
{
out[i]=frame[i];
}
delete [] frame;
//***********convert Array of int to Array of char ************
char* int2char = new char[taille];
for (int i=0; i<taille+1;i++)
{
int2char[i]=out[i];
}
//delete [] int2char;
//***********convert Array of char to STRUCT ************
PCryptDATA t; //Re-make the struct
memcpy(&t, int2char, sizeof(t));
}
您能否帮我找出运行时出现此问题的原因。
【问题讨论】:
-
您在
out和int2char的末尾写了一个字符:大小应该是taille+1,或者循环边界应该是taille。此外,p.size和sizeof(p)之间存在一些混淆。 -
C++ 中的 C 风格函数被严重反对。你有 STL 和迭代器,你为什么要手动编写循环并玩指针?
-
另外,
char通常是 1 个字节,而int是两个字节。通过将 int 复制到 char 数组中,您将破坏数据。 -
@ Mike Seymour,我不明白你注意到 p.size 和 sizeof(p) 之间有什么混淆!!
-
@Panagiotis Kanvos,我必须尊重以 char* 作为成员的结构,这就是为什么我必须手动编写循环。您能告诉我如何处理 int 数组到 char 数组的转换吗?
标签: c++ visual-c++ heap-memory