为什么不是这样的结果低价值? [英] Why isn't the result of this cast an lvalue?

查看:146
本文介绍了为什么不是这样的结果低价值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一些建议,这个奇怪的行为 - 让我们有这个代码:

I need some advice with this strange behavior – lets have this code:

int ** p;

这样编译没有任何麻烦:

This compiles without any trouble:

p++;

但是:

((int**)p)++;

给我这个错误消息:错误:需要作为增量操作数的lvalue

Gives me this error message: "error: lvalue required as increment operand".

我已经将 p 转换为它已经存在的类型,没有任何变化,那么问题是什么?这是我遇到的问题的简化版本,当我试图编译一个旧的
版本的 gdb 。所以我想,这是有效的,有所改变。任何想法第二个例子是什么错了?

I am casting to p to the type it already is, nothing changes, so what is the problem? This is simplified version of problem I came across, when I was trying to compile one old version of gdb. So I suppose, that this worked and something changed. Any idea what is wrong with the second example?

推荐答案

旧版本的gcc支持称为lvalue casts的东西 - 如果你转换的​​东西是左值,结果是左右,可以这样对待。它的主要用途是允许您将指针增加对应于不同大小的金额:

Old versions of gcc support something called "lvalue casts" -- if you cast something that is an lvalue the result is an lvalue and can be treated as such. The main use for it is allowing you to increment a pointer by an amount corresponding to a different size:

int *p;
++(char *)p;  /* increment p by one byte, resulting in an unaligned pointer */

gcc v3.0中删除,并在gcc v4.0中删除

This extension was deprecated some time around gcc v3.0 and removed in gcc v4.0

要在gcc的更新版本中执行相同的操作,您需要做一个添加和赋值增量)将指针转换为添加类型并返回给赋值:

To do the equivalent thing in more recent versions of gcc, you need do an addition and assignment (instead of an increment) casting the pointer to the type for the addition and back for the assignment:

p = (int *)((char *)p + 1);

请注意,在这之后尝试取消引用指针是未定义的行为,所以不要指望它任何有用的。

Note that trying to dereference the pointer after this is undefined behavior, so don't count on it doing anything useful.

这篇关于为什么不是这样的结果低价值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆