在取消引用的指针上进行后增量? [英] Post-increment on a dereferenced pointer?

查看:26
本文介绍了在取消引用的指针上进行后增量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在尝试理解 C 中指针的行为时,我对以下内容感到有些惊讶(下面的示例代码):

Trying to understand the behaviour of pointers in C, I was a little surprised by the following (example code below):

#include <stdio.h>

void add_one_v1(int *our_var_ptr)
{
    *our_var_ptr = *our_var_ptr +1;
}

void add_one_v2(int *our_var_ptr)
{
    *our_var_ptr++;
}

int main()
{
    int testvar;

    testvar = 63;
    add_one_v1(&(testvar));         /* Try first version of the function */
    printf("%d
", testvar);        /* Prints out 64                     */
    printf("@ %p

", &(testvar));

    testvar = 63;
    add_one_v2(&(testvar));         /* Try first version of the function */
    printf("%d
", testvar);        /* Prints 63 ?                       */
    printf("@ %p
", &(testvar));   /* Address remains identical         */
}

输出:

64
@ 0xbf84c6b0

63
@ 0xbf84c6b0

第二个函数 (add_one_v2) 中的 *our_var_ptr++ 语句究竟做了什么,因为它显然不同于 *our_var_ptr = *our_var_ptr +1?

What exactly does the *our_var_ptr++ statement in the second function (add_one_v2) do since it's clearly not the same as *our_var_ptr = *our_var_ptr +1?

推荐答案

由于运算符优先规则和 ++ 是后缀运算符的事实,add_one_v2()确实取消了对指针的引用,但是 ++ 实际上被应用于指针本身.但是,请记住,C 始终使用值传递:add_one_v2() 正在增加指针的本地副本,这对存储在的值没有任何影响那个地址.

Due to operator precedence rules and the fact that ++ is a postfix operator, add_one_v2() does dereference the pointer, but the ++ is actually being applied to the pointer itself. However, remember that C always uses pass-by-value: add_one_v2() is incrementing its local copy of the pointer, which will have no effect whatsoever on the value stored at that address.

作为测试,将 add_one_v2() 替换为这些代码位,看看输出如何受到影响:

As a test, replace add_one_v2() with these bits of code and see how the output is affected:

void add_one_v2(int *our_var_ptr)
{
    (*our_var_ptr)++;  // Now stores 64
}

void add_one_v2(int *our_var_ptr)
{
    *(our_var_ptr++);  // Increments the pointer, but this is a local
                       // copy of the pointer, so it doesn't do anything.
}

这篇关于在取消引用的指针上进行后增量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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