我为什么不能做算术上的一个空指针的投? [英] Why can I not do arithmetic on a cast of a void pointer?
问题描述
void foo(void *ptr, int numBytes)
{
(char*)ptr += numBytes;
}
这并不在C编译我所知道的替代品。但为什么这个不行?有什么问题?
This doesn't compile in C. I know the alternative. But why does this not work? What is the problem?
推荐答案
问题
问题是,(字符*)PTR
不会产生一个的左值的,这意味着价值不能被修改 - 一眼就能看出来作为演员的临时结果,演员将产生的右值的类型的char *
。
The problem is that (char*)ptr
will not yield an lvalue, meaning that the value cannot be modified - one can see it as a temporary result of the cast, the cast will yield a rvalue of type char*
.
这是语义上一样,如果你不得不在下面的例子中,铸造产生一个临时的价值,这样的价值不能被赋予一个新的值。
It's semantically the same as if you'd have the below example, a cast yields a temporary value, such a value cannot be assigned a new value.
int x = 123;
(float)x += 0.12f; /* (1), illegal */
/* ^-- sementically equivalent to `123.f += 0.12f` */
解决方案
在你的问题,你都表示你已经知道一种解决方法这个问题,但我想明确写入该解决方案显示一个如何修改 PTR $ C $的价值C>即使蒙上产生不可修改的值。
In your question you have stated that you already know a workaround to this problem, but I'd like to explicitly write the solution to show how one can modify the value of ptr
even when casts yields non-modifiable values.
- 取地址你的指向void 的
- 施放此地址到的指针指向char 的
- 解引用该指针,产生的字符指针的
- 修改此收益率的左值的,如果原来的
无效*
是类型的char *
- Take the address of your pointer to void,
- cast this address to a pointer to pointer to char,
- dereference that pointer, yielding a pointer to char,
- modify this yield lvalue as if the original
void*
was of typechar*
*((char**)&ptr) += numbytes; // make `ptr` move forward `numbytes`
(注意:当解引用指针,你得到的左值的,否则这将是不可能改变的值的指出的值位于存储在指针中的地址。)
( Note: When dereferencing a pointer you get an lvalue, otherwise it would be impossible to change the value of the pointed to value located at an address stored in a pointer. )
这篇关于我为什么不能做算术上的一个空指针的投?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!