c - 在函数调用与指向堆栈变量的指针之间使用传输值(按值?)

标签 c variables pointers stack pass-by-value

函数调用之间的“传递值”(按值?对英文术语不是百分百确定)是什么意思。给我举个例子,假设我使用指向堆栈变量的指针。

“值(value)转移”这个概念我真的不懂。该函数应该返回给另一个函数什么?

如果我像下面的例子那样使用指针,我只是传输指针地址?那么我该如何使用带有指向堆栈变量指针的传输值呢?

void fun1(){
  int x = 44;
  int *y = &x;
}

void fun2(){
  int *y;
  }

来自第一个答案:

   void fun1(){
        int x = 44;
        fun2( &x );
        printf( "%d\n", x );       // prints 55
    }

    void fun2( int *value ){
        printf( "%d\n", *value );  // prints 44
        *value = 55;               // changes the value of `x` in `fun1`

}

对我来说,我似乎只是将指向堆栈变量 (x) 的指针传输到 fun2?所以实际问题是:如何使用指向堆栈变量的指针在函数调用之间传输值?

您可能已经回答了这个问题?但我想确定这一点,如果我做对了,那就更糟了,所以这是我目前的想法:我首先将一个指针从 fun1 发送到 fun2 到堆栈变量 x。当调用 fun2 时,我通过 *value = 55 将 int x = 44 的值更新为 55,而 *value 是一个指向堆栈变量的指针,所以我实际上是在指向 a 的指针的帮助下更新了变量 x 的值堆栈变量。但是我在哪里使用这种指向堆栈变量的指针技术在函数之间传递值。我是否在函数之间传递值?我不这么认为,如果我这样做,我应该向另一个函数返回一些东西。现在看来我只是在函数调用之间更新了一个变量?但也许问题已经得到解答?但我仍然有点困惑函数调用之间传递值的含义。

最佳答案

如果您希望 fun2 能够更改 fun1 中的变量 x,则将指向 x 的指针传递给 fun2 像这样

// This code demonstrates "pass by address" which (for the C programming
// language) is the same as "pass by reference". 

void fun1(){
    int x = 44;
    fun2( &x );
    printf( "%d\n", x );       // prints 55
}

void fun2( int *value ){
    printf( "%d\n", *value );  // prints 44
    *value = 55;               // changes the value of `x` in `fun1`
}

如果你传递x作为参数而不是x的地址,那么fun2将不能改变x的值x fun1 有。

// This code demonstrates "pass by value". fun2 is given the value of x but 
// has no way to change fun1's copy of x.

void fun1( void ){
    int x = 44;
    fun2( x );
    printf( "%d\n", x );      // prints 44
}

void fun2( int value ){
    printf( "%d\n", value );  // prints 44
    value = 55;               // has no effect on `x` in `fun1`
}

关于c - 在函数调用与指向堆栈变量的指针之间使用传输值(按值?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27030065/

相关文章:

c - 如何理解 c 中的模数

c - 用指针修改结构体数组

variables - 在 Go var 声明中显式提供类型失败,而隐式工作

c - 不兼容的整数到指针转换将 'char' 传递给类型 'const char *' 的参数

c - malloc 和全局变量声明在 C 中将它们的变量分配到哪里?

variables - 带有 GUI 的 Powershell 不会设置变量

javascript - if-else JavaScript 不工作

c - C中的数组是通过指针使用的吗?

c++ - C/C++ 中的指针

c++ - 当 vector 需要更多内存并分配内存时,指针会发生什么变化?