c - 传递地址,但它的工作方式类似于 C 中的按值调用?

标签 c pointers call-by-value

您好,我是 C 编程语言的初学者。最近我读到了按值(value)调用和按地址调用。我了解到,在调用中,被调用函数的地址变化反射(reflect)了被调用者。然而,下面的代码并不像那样工作。

int x = 10,y = 20;
void change_by_add(int *ptr) {
    ptr = &y;
    printf("\n Inside change_by_add\t %d",*ptr);
    // here *ptr is printing 20
}

void main(){
    int *p;
    p = &x;
    change_by_add(p);
    printf("\nInside main\t %d", *p);
    // here *p is still pointing to address of x and printing 10
}

当我传递地址时,为什么被调用函数所做的更改不能反射(reflect)调用者?

最佳答案

该函数正在为指针分配一个新地址,但指针本身是按值传递的,因为所有参数都在 C 中。要更改指针变量的值,必须传递指针本身的地址:

void change_by_add(int **ptr)
{
    *ptr = &y;
}

change_by_add(&p);

参见 C FAQ Question 4.8 .

C 中不存在按引用传递,但可以通过将要更改值的变量的地址传递给函数来实现。例如:

void add_to_int(int* a_value, int a_increment)
{
    *a_value += a_increment;
}

关于c - 传递地址,但它的工作方式类似于 C 中的按值调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23291591/

相关文章:

c - 如何在不使用 C++ STL 的情况下实现 C 中的 map 概念

C/C++ - uint8_t x :6 中冒号的用途是什么

java - 有没有办法保证真正引用的对象对调用者函数没有副作用?

c - Ncurses:比较输入和文本文件中选定的单词

c - 两个警告 : assignment makes integer from pointer without a cast and comparison between pointer and integer

c - 使用指针而不是索引更新数组

c++ - 如何使用指针从函数传递对象在堆上的地址

java - 为什么修改了 ArrayList 参数,但没有修改 String 参数?

c - 从管道中读取整数会跳过 C 中的值