什么是C语言中的引用传递?

用C编程语言通过引用传递的是作为参数发送的地址。

算法

下面给出一种算法,以解释C语言中按值传递的工作方式。

START
Step 1: Declare a function with pointer variables that to be called.
Step 2: Declare variables a,b.
Step 3: Enter two variables a,b at runtime.
Step 4: Calling function with pass by reference.
      jump to step 6
Step 5: Print the result values a,b.
Step 6: Called function swap having address as arguments.
      i. Declare temp variable
      ii. Temp=*a
      iii. *a=*b
      iv. *b=temp
STOP

示例

以下是使用引用传递交换两个数字的C程序-

#include<stdio.h>
void main(){
   void swap(int *,int *);
   int a,b;
   printf("enter 2 numbers");
   scanf("%d%d",&a,&b);
   printf("Before swapping a=%d b=%d",a,b);
   swap(&a, &b);
   printf("after swapping a=%d, b=%d",a,b);
}
void swap(int *a,int *b){
   int t;
   t=*a;
   *a=*b; // * a =(* a + * b)–(* b = * a);
   *b=t;
}
输出结果

执行以上程序后,将产生以下结果-

enter 2 numbers 10 20
Before swapping a=10 b=20
After swapping a=20 b=10

让我们再举一个例子来了解更多关于引用传递的信息。

下面是C程序,通过使用按引用调用或按引用传递,为每个调用将值增加5。

#include <stdio.h>
void inc(int *num){
   //增量完成
   //在存储num值的地址上。
   *num = *num+5;
   // return(* num);
}
int main(){
   int a=20,b=30,c=40;
   // 传递变量a,b,c的地址
   inc(&a);
   inc(&b);
   inc(&c);
   printf("Value of a is: %d\n", a);
   printf("Value of b is: %d\n", b);
   printf("Value of c is: %d\n", c);
   return 0;
}
输出结果

执行以上程序后,将产生以下结果-

Value of a is: 25
Value of b is: 35
Value of c is: 45