在一个语句中取消引用和前进指针?

发布于 2024-07-26 03:50:41 字数 194 浏览 1 评论 0原文

我正在从字节数组中读取数据,如下所示:

int* i = (int*)p;
id = *i;
i++;

如果我错了,请纠正我,但是 ++ 优先于 *,因此可以在同一语句中组合 *i 和 i++ 吗? (例如 *i++)

(这在技术上是不安全的 C#,而不是 C++,p 是一个字节*)

I'm reading from a byte array as follows:

int* i = (int*)p;
id = *i;
i++;

correct me if I'm wrong, but ++ has precedence over *, so is possible to combine the *i and i++ in the same statement? (e.g. *i++)

(this is technically unsafe C#, not C++, p is a byte*)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

看海 2024-08-02 03:50:41

我相信

id = *i;
i++;

id = *i++;

是等价的。

++ 运算符用作后缀(例如i++)时,返回变量在递增之前的值。


我对反射器输出感到有些困惑,

unsafe class Test
{
    static public void Test1(int p, out int id)
    {
        int* i = (int*)(p);
        id = *i;
        i++;
    }

    static public void Test2(int p, out int id)
    {
        int* i = (int*)(p);
        id = *i++;
    }
}

其中的输出

public static unsafe void Test1(int p, out int id)
{
    int* i = (int*) p;
    id = i[0];
    i++;
}

public static unsafe void Test2(int p, out int id)
{
    int* i = (int*) p;
    i++;
    id = i[0];
}

显然不相等。

I believe that

id = *i;
i++;

and

id = *i++;

are equivalent.

The ++ operator, when used as a suffix (e.g. i++), returns the value of the variable prior to the increment.


I'm somewhat confused by the reflector output for

unsafe class Test
{
    static public void Test1(int p, out int id)
    {
        int* i = (int*)(p);
        id = *i;
        i++;
    }

    static public void Test2(int p, out int id)
    {
        int* i = (int*)(p);
        id = *i++;
    }
}

which comes out as

public static unsafe void Test1(int p, out int id)
{
    int* i = (int*) p;
    id = i[0];
    i++;
}

and

public static unsafe void Test2(int p, out int id)
{
    int* i = (int*) p;
    i++;
    id = i[0];
}

which clearly are not equivalent.

美胚控场 2024-08-02 03:50:41

id = *i++

会做你想做的。

++ 取消引用后修改指针。

编辑:
正如 Eric 指出的,根据规范,取消引用后不会发生 ++。 i++ 递增 i 并返回其初始值,因此规范定义的行为是增量发生在取消引用之前。 无论您查看取消引用之前还是之后发生的增量,id = *i++ 的可见行为都是相同的。

id = *i++

will do what you want.

++ modifies the pointer after the dereference.

EDIT:
As Eric points out, per the spec, ++ does not happen after dereference. i++ increments i and return its initial value, so the spec defined behavior is the increment happens prior to dereference. The visible behavior of id = *i++ is the same whether you view the increment happening before or after dereference.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文