[英]Cast void* to char*
I have a char *
who points to the structure.我有一个指向结构的
char *
。 Here is my structure:这是我的结构:
struct prot
{
int size;
unsigned short codeAction;
void *data;
};
I recovered size
and codeAction
, but now I want to recover data
.我恢复了
size
和codeAction
,但现在我想恢复data
。 And when I cast my last 8 bytes I have nothing in it.当我投射最后 8 个字节时,我什么都没有。
The following code is just a test, it's a bad code:下面的代码只是一个测试,这是一个糟糕的代码:
char lol[4];
for (int i = 0; i < 4; i++)
lol[i] = test[i];
int size = *(int*)lol;
char loli[2];
int index = 0;
for (int i = 4; i < 6; i++)
{
loli[index] = test[i];
index++;
}
int code = *(short*)loli;
char lolo[8];
index = 0;
for (int i = 6; i < size; ++i)
{
lolo[index] = test[i];
index++;
}
void *newData = (char *)lolo; // how can I cast it?
How I can display the content of newData
?如何显示
newData
的内容?
Your problem is that when casting lolo
you actually cast a pointer to the char array you defined.您的问题是,在转换
lolo
您实际上是在转换一个指向您定义的 char 数组的指针。 So the result of the cast would be a char
pointer to the first cell of the array.所以转换的结果将是一个指向数组第一个单元格的
char
指针。
Why don't you just use this as a struct and access the fields regularly?为什么不直接将其用作结构并定期访问字段?
Anyway, you want to use lolo
as a 64 bit type pointer and the access what's in it.无论如何,您想将
lolo
用作 64 位类型的指针并访问其中的内容。
void* newData = *((uint64_t*)lolo)
Besides, don't loop until size
in the last for
loop, loop only 8 times, until lolo
is full.此外,不要循环直到最后一个
for
循环中的size
,只循环8次,直到lolo
已满。 The number of bytes in newData
itself ( not what it points to) is constant, and is 4 bytes on 32bit machines, 8 bytes on 64bit ones. newData
本身的字节数(不是它指向的)是常数,在 32 位机器上是 4 个字节,在 64 位机器上是 8 个字节。
Last thing - index++
, not o++
.最后一件事 -
index++
,而不是o++
。 o
isn't defined, as much as I can see. o
没有定义,就我所见。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.