[英]What does this do exactly? [*(char*)p1]
I am not used to pointers because I started learning Pascal in high school and now I am upgrading myself to C. My request would be to explain me what should I think when I see something like this [*(char*)p1]
. 我不习惯使用指针,因为我从高中就开始学习Pascal,现在我将自己升级为C。我的要求是向我解释当我看到类似[*(char*)p1]
东西时应该怎么看。 Don't be shy writing me quite a few lines :) 不要害羞地写给我几行:)
Thank you. 谢谢。
PS p1 is a const void *
. PS p1是const void *
。 To be more accurate. 更准确地说。
Assuming that [*(char*)p1]
is an array designator, (char*)
is used to cast p1
to make p1
char *
type. 假设[*(char*)p1]
是数组指示符,则使用(char*)
p1
转换p1
以使p1
char *
类型。 Then *
is used to dereference it to use value at the address ( p1
points to) as index to some array. 然后使用*
取消引用,以使用地址( p1
指向)上的值作为某个数组的索引。
[*(char*)p1]
is somewhat incomplete, there needs to be a variable name in front of it for the array subscription to make sense, such as for example foo[*(char*)p1]
. [*(char*)p1]
有点不完整,为了使数组订阅有意义,它前面必须有一个变量名,例如foo[*(char*)p1]
。
In that case, it means: 在这种情况下,这意味着:
char
value) 解引用该指针(给出一个char
值) Note that using a char
as index will make most compilers unhappy and cause it to emit a warning. 请注意,使用char
作为索引将使大多数编译器不满意,并使其发出警告。 That is because most often when a char
is used as an index, it happens by error, not by intent, and also because it is implementation-defined whether char
is signed or unsigned (so it is inherently non-portable, and you may end up indexing out of bounds by accident, if you assume the wrong one). 这是因为最常见的情况是,当将char
用作索引时,它是由于错误而不是出于意图而发生的,并且因为它是实现定义的,所以无论char
是带符号的还是无符号的(因此它本质上是不可移植的,您可能会结束如果您输入错误的索引,则会无意间超出索引范围)。
void *p1;
// pointer to void or generic pointer; //指向void或通用指针的指针; might be used when you want to be flexible about the data type 当您想灵活处理数据类型时可以使用
(char*)p1;
//typecast to a char pointer; //类型转换为char指针; you address the memory locatuion pointed to by P1 as char 您将P1指向的存储位置称为char
*(char*)p1;
//the value at the location pointed to by p1. // p1指向的位置处的值。
Hope this helps. 希望这可以帮助。
(char*)p1
is a typecast. (char*)p1
是类型转换。 This means, for this statement, we're treating p1
as a pointer to a character. 这意味着,对于此语句,我们将p1
视为指向字符的指针。 *(char*)p1
dereferences p1
, interpreting it as a char
type due to the typecast (char*)
. *(char*)p1
取消引用p1
,由于类型转换(char*)
而将其解释为char
类型。 A pointer points to a memory location, and dereferencing that pointer returns the value at the location in memory p1
points to. 指针指向一个内存位置,对该指针的取消引用将返回内存p1
指向的位置的值。 [*(char*)p1]
... Array access? [*(char*)p1]
...数组访问? is this a snippet from something larger? 这是更大的片段吗? This void*
to someOtherType*
conversion is common in C code, because malloc
, used to allocate memory dynamically, returns void*
. 这种void*
到someOtherType*
转换在C代码中很常见,因为用于动态分配内存的malloc
返回void*
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.