[英]Dereference operator gives different results than array offset operator with void*
The following C++ Win32 console program assigns an array to a pointer to void, and prints the results in two different ways:以下 C++ Win32 控制台程序将一个数组分配给指向 void 的指针,并以两种不同的方式打印结果:
// Foo.cpp : A Win32 console application.
//
#include "stdafx.h"
typedef unsigned char elem_type;
#define ELEM_COUNT 4
int _tmain(int argc, _TCHAR* argv[])
{
elem_type *ary = new elem_type[ELEM_COUNT];
for (int i = 0; i < ELEM_COUNT; i++)
{
ary[i] = ((i + 1) * 5); // multiples of 5
}
void *void_ary = ary;
for (int i = 0; i < ELEM_COUNT; i++)
{
printf("void_ary[%d] is %u\t", i, ((elem_type*)void_ary)[i]);
printf("*(void_ary+%d) is %u\n", i, *((elem_type*)(void_ary))+i);
}
void *allocd_ary;
return 0;
}
Here is the output:这是 output:
void_ary[0] is 5 *(void_ary+0) is 5
void_ary[1] is 10 *(void_ary+1) is 6
void_ary[2] is 15 *(void_ary+2) is 7
void_ary[3] is 20 *(void_ary+3) is 8
Using square brackets prints the result that I expected.使用方括号打印出我预期的结果。 But dereferencing pointer offsets does not, even though the array is being typecast .
但是取消引用指针偏移量不会,即使数组正在被类型转换。
Why the discrepancy?为什么会出现差异?
Well that is because you are dereferencing the value then adding 'i' to the result.嗯,那是因为您要取消引用该值,然后将“i”添加到结果中。 You need some more parenthesis around the pointer cast or using static_cast which is more obvious.
您需要在指针转换或使用更明显的 static_cast 周围添加更多括号。
As in:如:
*(static_cast<elem_type*>(void_ary)+i)
printf("*(void_ary+%d) is %u\n", i, *((elem_type*)(void_ary))+i);
Here it seems that you are dereferencing the value BEFORE adding i
to it.在这里,您似乎在向其添加
i
之前取消引用该值。 This will cause to get always the first element of the array (since you are dereferencing the same pointer 5 times) and add i
to it.这将导致始终获取数组的第一个元素(因为您对同一个指针取消引用 5 次)并将
i
添加到它。
Try with:尝试:
*((elem_type*)(void_ary)+i)
Your expression don't mean the same thing.你的表情不是同一个意思。 What you write as
你写成什么
*(void_ary+i)
Is not actually that.其实不是那样的。 In fact it is
事实上它是
void_ary[0]+i
according to your printf
notation.根据您的
printf
符号。
If you write如果你写
*((elem_type*)(void_ary))+i
as作为
*((elem_type*)(void_ary)) + i
then I think it becomes more clear.然后我认为它变得更加清晰。 You are looking for:
您正在寻找:
*((elem_type*)(void_ary)+i)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.