Cplusplus-cpp-function-call-by-pointer
提供:Dev Guides
ポインターによるC ++関数呼び出し
引数を関数に渡す*ポインタによる呼び出し*メソッドは、引数のアドレスを仮パラメータにコピーします。 関数内では、呼び出しで使用される実際の引数にアクセスするためにアドレスが使用されます。 これは、パラメーターに加えられた変更が、渡された引数に影響することを意味します。
ポインターで値を渡すために、引数ポインターは他の値と同じように関数に渡されます。 したがって、次の関数* swap()*のように、関数のパラメーターをポインター型として宣言する必要があります。これは、引数が指す2つの整数変数の値を交換します。
//function definition to swap the values.
void swap(int *x, int *y) {
int temp;
temp = *x;/*save the value at address x*/
*x = *y;/*put y into x*/
*y = temp;/*put x into y*/
return;
}
C ポインターの詳細を確認するには、link:/cplusplus/cpp_pointers [C ポインター]の章を確認してください。
今のところ、次の例のようにポインタで値を渡すことで関数* swap()*を呼び出しましょう-
#include <iostream>
using namespace std;
//function declaration
void swap(int *x, int *y);
int main () {
//local variable declaration:
int a = 100;
int b = 200;
cout << "Before swap, value of a :" << a << endl;
cout << "Before swap, value of b :" << b << endl;
/*calling a function to swap the values.
* &a indicates pointer to a ie. address of variable a and
*&b indicates pointer to b ie. address of variable b.
*/
swap(&a, &b);
cout << "After swap, value of a :" << a << endl;
cout << "After swap, value of b :" << b << endl;
return 0;
}
上記のコードがファイルにまとめられ、コンパイルされて実行されると、次の結果が生成されます-
Before swap, value of a :100
Before swap, value of b :200
After swap, value of a :200
After swap, value of b :100