++上在C中取消引用指针? [英] ++ on a dereferenced pointer in C?

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

问题描述

试图理解C指针的行为,我是通过以下(例如:code以下)有些惊讶:

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\n", testvar);        /* Prints out 64                     */
    printf("@ %p\n\n", &(testvar));

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

/*

OUTPUT:

64
@ 0xbf84c6b0

63
@ 0xbf84c6b0

*/

究竟做了 * our_var_ptr ++ 在第二个函数语句( add_one_v2 )做,因为它显然不一样为 * 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?

推荐答案

由于操作precedence规则和事实,即 ++ 是一个后缀操作符, 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()与code的这些位,看看输出是如何受到影响:

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.
}

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

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