代码之家  ›  专栏  ›  技术社区  ›  victory

更改指针指向的int变量

  •  2
  • victory  · 技术社区  · 7 年前

    我有点新手,指针仍然给我带来麻烦。我想更改的值 int ,我从函数中的参数(作为指针)获得。

    #include <stdio.h>
    
    bool function(int* a){
    
        a++;
    
        printf("%d",*a); //getting some big number, maybe address. If i did not use a++; I get just normal a, unchanged.
    
        return false;
    }
    
    4 回复  |  直到 7 年前
        1
  •  6
  •   Eduardo Pascual Aseff    4 年前

    问题是您正在递增语句中的指针(而不是指针所指向的值) a++ 。如果要增加参数的值,应首先取消对其的引用:

    (*a)++; //instead of a++;
    

    Printf并不是精确地打印地址,只是打印存储在参数旁边的整数(可以是整数,也可以是其他值)的值 a

        2
  •  3
  •   0x51ba    7 年前

    您需要取消对指针的引用,以通过使用 *a 。然后可以增加该值。所以你的代码应该是 (*a)++ 而不是 a++ (在您的情况下,您只是增加地址并尝试访问内存中的下一个位置)。

        3
  •  3
  •   sg7 Krafty Coder    7 年前

    指针是一个变量,它包含另一个变量在内存中的地址。我们可以有一个指向任何变量类型的指针。

    间接或取消引用运算符 * 给出指针指向的对象的内容。

    一元运算符或一元运算符 & 给出变量的地址。

    在程序中,递增指针 a :

     a++;
    

    那次行动 不是 影响指针指向的对象。

    如果要增加参数的值,应使用解引用操作符解引用指针 * 然后增加值。

    (*a)++;
    

    这是一个小例子,在实践中,你可以通过一个指针来改变变量的值。

    #include <stdio.h>
    
    void function(int* a){
    
        (*a)++;          // dereference the pointer `a` and increase the content of an object pointed to by the pointer by 1.
        (*a) = (*a) + 2; // dereference the pointer `a` and increase the content of an object pointed to by the pointer by 2.
    
        printf("\nprint from function (*a) = %d\n",(*a) ); 
    }
    
    int main(void)
    {
        int x = 7;
        int *p = &x;             // pointer to variable x 
    
        printf("x = %d\n", x );  //     x = 7
    
        function(p); // calling with pointer p as argument
    
        printf("x = %d\n", x );  //    x = 10
    
        function(&x); // calling with pointer &x as argument  
    
        printf("x = %d\n", x );  //    x = 13       
    
        return 0;
    }
    

    输出:

    x = 7                                                                                                               
    
    print from function (*a) = 10                                                                                       
    x = 10                                                                                                              
    
    print from function (*a) = 13                                                                                       
    x = 13                                                                                                              
    
        4
  •  1
  •   HubballiHuli    7 年前

    (*a)++ 相反 函数接收指针作为参数。如果 ++ 与指针变量一起使用,然后对于64位int变量,它将递增到4字节并保存该内存地址,如果该位置中没有值,则会打印出一个垃圾值,这就是为什么会得到这么大的数字。跟随 this link 了解指针算法的基本知识。