[英]Arithmetic pointer with void*
So I need to create a call to strange_step that results in it printing out the if statement: 所以我需要创建一个对strange_step的调用,导致它打印出if语句:
void strange_step(void* value)
{
if(*(int*)(value+5) == 15)
printf("4: Illinois\n");
else
printf("4: ERROR\n");
}
I've tried the following (since to my knowledge, with gcc, it treats void* like a char* so increments 1 byte): 我尝试了以下操作(据我所知,使用gcc,它将void *视为char *,因此将其增加1个字节):
int arr[10];
arr[4] = 15;
arr[5] = 15;
arr[3] = 15;
arr[2] = 15;
arr[6] = 15;
arr[7] = 15;
arr[8] = 15;
arr[9] = 15;
//arr[10] = 15;
strange_step(arr);
But that just seems to print out random numbers. 但这似乎只是打印出随机数。 What am I missing?
我想念什么?
You've got two issues there: 您那里有两个问题:
void*
is not allowed void*
执行指针算术 int
from a non-aligned pointer may result in an error int
可能会导致错误 However, if you would like to shoehorn 15 into the proper offset, you could do this: 但是,如果您想将鞋拔号15调整到适当的偏移量,则可以这样做:
char data[32];
*((int*)&data[5]) = 15;
strange_step(data);
This prints what you expect ( demo ). 这将打印您期望的内容( 演示 )。 However, unless you modify
strange_step
to stop reading unaligned data, your program would rely on undefined behavior. 但是,除非您修改
strange_step
以停止读取未对齐的数据,否则程序将依赖于未定义的行为。
When you type value+5
, it's moving the pointer 5 bytes before casting it as an int*
. 当您键入
value+5
,它将指针移动5个字节,然后将其强制转换为int*
。 Depending on your platform, an int
is 4 or 8 bytes. 根据您的平台,
int
是4或8个字节。 On a little-endian machine 在小端机上
0F0000000F0000000F0000000F0000000F0000000F0000000F0000000F000000
^ ^
value value+5
You're moving off the int
boundary, so you're probably finding values that are off by some multiple of 256. I'm guessing you're seeing 251658240 a lot? 您正在移出
int
边界,因此可能发现的值是256的某个倍数。我猜您看到的是658658240很多吗? That's why. 这就是为什么。
You need to change the function to: 您需要将功能更改为:
void strange_step(void* value)
{
// Treat the input pointer as an `int*`.
int* ip = (int*)value
// Use the 6-the value of the array.
// You could also use if ( ip[5] == 15 )
if(*(ip+5) == 15)
printf("4: Illinois\n");
else
printf("4: ERROR\n");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.