C 指针(简单程序)

标签 c pointers

所以我现在正在学习 C 中的指针,我正在阅读的书中有一个示例程序,但是当我运行它时它不能正常工作。代码是:

 #include <stdio.h>
 #include <stdlib.h>
     void go_south_east(int *lat, int *lon)
    {
    *lat = *lat - 1;
    *lon = *lon + 1;
}
 int main(){
    int latitude = 64;
    int lontitude = -32;
    go_south_east(&latitude, &lontitude);
    printf("Now at [%i, %i]\n", latitude, lontitude);
    return 0;
    system("pause");
}

想法是这些“纬度和经度”是一个对象的坐标,我们想把它向东南移动。我个人认为这是错误的行:

 go_south_east(&latitude, &lontitude);

为什么我们需要变量的地址?? 还有一个关于这一行的问题:

  printf("Now at [%i, %i]\n", latitude, lontitude);

这里的 %i 是什么意思?整数值不应该是 %d 吗?

最佳答案

go_south_east(&latitude, &lontitude);

我们需要变量的地址,因为您通过引用传递它们,因为您想要修改它们的值。你不想只给函数两个数字,你希望它能够改变它们。因此,您需要通知函数这些变量所在的位置(它们的地址),以便函数可以就地修改它们的值。

它工作正常,因为输出是 Now at [63, -31],所以函数正确地红色传递的值并更新它们。

关于C 指针(简单程序),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21388786/

相关文章:

C 结构指针

c - 了解 Newt Widget Kit 中指向指针的 Const 指针

c - 读取大文件时分配数组的最佳方法是什么

c - 如果补丁无法应用,如何导致构建系统编译失败

c - 源代码中初始化结构体时出错

c - C中的网络; bind() 需要它的论点吗?

c++ - 尝试将指向 int 的指针传递给需要指向 long 的指针的函数,如何执行此操作

c - 二维数组,按总和对行进行排序

c++ - libjpeg 中的指针对齐

c - 需要检查查询字符串之前是否存在任何扩展名