原文: https://beginnersbook.com/2014/01/c-passing-pointers-to-functions/
在本教程中,您将学习如何将指针作为参数传递给函数。要理解这个概念,你必须对 C 编程中的指针和函数有基本的了解。
就像任何其他参数一样,指针也可以作为参数传递给函数。让我们举一个例子来了解这是如何完成的。
示例:在 C 编程中将指针传递给函数
在这个例子中,我们传递一个指向函数的指针。当我们将指针而不是变量作为参数传递时,则传递变量的地址而不是值。因此,使用指针的函数所做的任何更改,都是在传递的变量的地址处永久进行的。这种技术在 C 中称为按引用调用。
尝试没有指针的同一个程序,你会发现奖金金额不会反映在工资中,这是因为函数所做的更改将对函数的局部变量进行。当我们使用指针时,值会在变量的地址处更改。
#include <stdio.h>void salaryhike(int *var, int b){*var = *var+b;}int main(){int salary=0, bonus=0;printf("Enter the employee current salary:");scanf("%d", &salary);printf("Enter bonus:");scanf("%d", &bonus);salaryhike(&salary, bonus);printf("Final salary: %d", salary);return 0;}
输出:
Enter the employee current salary:10000Enter bonus:2000Final salary: 12000
示例 2:使用指针交换两个数字
这是最流行的示例之一,显示如何使用按引用调用交换数字。
尝试没有指针的程序,你会看到数字没有交换。原因与我们在第一个例子中看到的相同。
#include <stdio.h>void swapnum(int *num1, int *num2){int tempnum;tempnum = *num1;*num1 = *num2;*num2 = tempnum;}int main( ){int v1 = 11, v2 = 77 ;printf("Before swapping:");printf("\nValue of v1 is: %d", v1);printf("\nValue of v2 is: %d", v2);/*calling swap function*/swapnum( &v1, &v2 );printf("\nAfter swapping:");printf("\nValue of v1 is: %d", v1);printf("\nValue of v2 is: %d", v2);}
输出:
Before swapping:
Value of v1 is: 11
Value of v2 is: 77
After swapping:
Value of v1 is: 77
Value of v2 is: 11
