简体   繁体   English

为什么在这种情况下将void指针强制转换为char指针不起作用

[英]Why casting void pointer to char pointer doesn't work in this situation

I've got void pointer which I want to do pointer arithmetic on it. 我有空指针,我想对其进行指针运算。 to do so, I want to cast it to a char pointer. 为此,我想将其强制转换为char指针。

( char * ) buf += current_size;

However when I do so, I get the following error: 但是,当我这样做时,出现以下错误:

error: lvalue required as left operand of assignment

I tried also adding parenthesis on the the whole left side, with no success. 我也尝试在整个左侧添加括号,但没有成功。 Why do I get this ? 为什么我得到这个?

Why do I get this 为什么我得到这个

Simply because the language rules state that a cast does not produce an lvalue even if the operand is one . 仅仅因为语言规则规定, 即使操作数为1 ,强制转换也不会产生左值。

ISO/IEC 9899:201x - n1570 ISO / IEC 9899:201x-n1570

In a footnote, page 91 在脚注中,第91页

A cast does not yield an lvalue. 强制转换不会产生左值。

You can avoid the warning by writing the assignment operator out: 您可以通过写出赋值运算符来避免警告:

buf = (char *)buf + current_size;

Part of the reason you get the warning is that sizeof(void) is undefined and you cannot do arithmetic on void * . 收到警告的部分原因是sizeof(void)未定义,并且无法对void *进行算术运算。 Beware: GCC has an extension whereby it treats the code as if sizeof(void) == 1 , but that is not in the C standard. 当心:GCC有一个扩展,它将代码视为sizeof(void) == 1 ,但这不是C标准。

The cast on the LHS of the assignment has no effect on the assignment. 作业的LHS上的转换对作业没有影响。

Because it's invalid, you can't do this. 因为它无效,所以您不能这样做。 If you want to achieve this, either 如果您想实现这一目标,

declare buf as a char pointer; 声明buf为char指针; or use a temporary variable: 或使用一个临时变量:

char *tmp = buf; // note you don't need the casting, void * works with everything
tmp += current_size;
buf = tmp;

Edit: as others also suggested, you can even remove that ugly tmp: 编辑:正如其他人也建议的那样,您甚至可以删除该丑陋的tmp:

buf = (char *)buf + current_size;

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

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