简体   繁体   English

算术的铸造指针 - C

[英]Casting pointers for arithmetic - C

If I have a void * x, but I want to cast it to a char *, so that the ++ operator will make it point to the next byte and not the next 4 byte block. 如果我有一个void * x,但是我想将它转换为char *,那么++运算符将指向下一个字节而不是下一个4字节块。

However, when I do: 但是,当我这样做时:

(char *) x -= byte_length;

The compiler complains: 编译器抱怨:

Error, lvalue required as left value of assignment.

Where am I going wrong please? 我哪里出错了? Thanks. 谢谢。

I would do it like this: 我会这样做:

 x = (char*)x - byte_length;

Cast x to char* , then apply the offset, then assign back to x . xchar* ,然后应用偏移量,然后分配回x Since void* is assignment compatible with all pointer types no further cast is needed. 由于void*与所有指针类型兼容,因此不需要进一步转换。

(char *)x evaluates to a temporary with the same value as x but a different type. (char *)x计算为临时值,其值与x相同,但类型不同。 The compiler won't allow -= on a temporary. 编译器不允许-=临时。 Do

x = (char *)x - byte_length;

The situation is analogous to the following: 情况类似于以下情况:

short x = 0;
(long)x += 1;     // invalid; (long)x is a temporary
x = (long)x + 1;  // works

Do something like this: 做这样的事情:

void* x;
char* cx = (char*)x;
cx -= byte_length;
x = cx;
(char*) x -= byte_length;

In this statement, (char*) x creates a temporary value with char* as type. 在此语句中, (char*) x创建一个临时值,其中char*为type。 You can only assign to variables, or more precisely, references (or an lvalue according to your compiler). 您只能分配给变量,或者更确切地说,分配引用 (或根据编译器的lvalue )。

One way to get a reference to it is casting the address of x to char* and dereferencing that: 获取引用的一种方法是将x地址转换为char*并解除引用:

*(char*) &x -= byte_length;

(char*)x is a temporary value that has not address in memory. (char*)x是一个临时值,它没有在内存中寻址。 You can't do a -- to it, for the same reason that if you have int i , you can't do (i+5)++ . 你不能做--对它,因为如果你有int i ,你不能做(i+5)++

You should do x=(char*)x-byte_length; 你应该做x=(char*)x-byte_length; instead. 代替。

See also http://c-faq.com/ptrs/castincr.html 另见http://c-faq.com/ptrs/castincr.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM