什么是 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
让我们再举一个例子来详细了解按引用传递。
示例
下面是使用按引用传递或按引用传递进行每次调用增值 5 的 C 语言程序。
#include <stdio.h>
void inc(int *num){
//increment is done
//on the address where value of num is stored.
*num = *num+5;
// return(*num);
}
int main(){
int a=20,b=30,c=40;
// passing the address of variable a,b,c
inc(&a);
inc(&b);
inc(&c);
printf("Value of a is: %d
", a);
printf("Value of b is: %d
", b);
printf("Value of c is: %d
", c);
return 0;
}输出
执行上述程序后,会生成以下结果 −
Value of a is: 25 Value of b is: 35 Value of c is: 45
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP