C:在函数中使用指针时,作为输入使用*指针递增指针值++不起作用 [英] c: when using a pointer as input in a function incrementing the pointers value by using *pointer++ doesn't work

查看:147
本文介绍了C:在函数中使用指针时,作为输入使用*指针递增指针值++不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

虽然我是学C(我很新的话),我与指针玩弄。在这里,你可以看到我的code:

 的#include<&stdio.h中GT;无效的变化为(int * I)
{
    * I + = 1;
}诠释的main()
{
    INT NUM = 3;    的printf(%d个\\ N,NUM);
    改变(试验#);
    的printf(%d个\\ N,NUM);    返回0;
}

我的目标是取代不重新分配它像这样递增num值:

  NUM =改变(NUM);

这就是为什么我是路过 NUM 的存储位置使用&安培; :所以它可以作为一个指针。这个版本的一切都在code之前是一样的。这是唯一不同的是,我说的 *我++; ,而不是说 * I + = 1;

现在我的问题是,为什么我不能说 *我++


解决方案

  

现在我的问题是,为什么我不能说* I ++


由于操作precedence, *我++ 是一样的 *(我++)

  *(我++);

相当于:

 为int * TEMP = I; //保存旧指针在临时变量。
我++; //增加指针
*温度; //取消引用旧指针值,有效的一个空操作。

这是不是你想要的。您需要使用(* I)++ ++(* I)。这将间接引用指针,然后启动对象的值递增指针指向。

While I was learning C (I am very new to it), I was playing around with pointers. Here you can see my code:

#include <stdio.h>

void change(int *i)
{
    *i += 1;  
}

int main()
{   
    int num = 3;

    printf("%d\n", num);
    change(&num);
    printf("%d\n", num);

    return 0;
}

My aim was to replace incrementing the num value without reassigning it like so:

num = change(num);

That's why I was passing the memory location of num using the &: so it could be used as a pointer. Before this version everything in the code was the same. The only thing that was different was that I said *i++; instead of saying *i += 1;

Now my question is why can't I say *i++?

解决方案

Now my question is why i can't say *i++

Due to operator precedence, *i++ is same as *(i++).

*(i++);

is equivalent to:

int* temp = i;  // Store the old pointer in a temporary variable.
i++;            // Increment the pointer
*temp;          // Dereference the old pointer value, effectively a noop.

That is not what you want. You need to use (*i)++ or ++(*i). These will dereference the pointer first and then increment the value of the object the pointer points to.

这篇关于C:在函数中使用指针时,作为输入使用*指针递增指针值++不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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