Loading

值传递和(地)址传递的区别


返回 我的技术栈(Technology Stack)



值传递

#include<stdio.h>

void swap(int a, int b) 
{
	int temp = a;
	a = b;
	b = temp;
}

int main(void)
{
	int a = 10;
	int b = 20;

	printf("%d\n", a);  //输出:10
	printf("%d\n", b); //输出:20

	//值传递  形参不影响实参的值
	swap(a,b);

	printf("%d\n", a); //输出:10
	printf("%d\n", b); //输出:20

	return 0;
}

程序原理解析如下:
image


(地)址传递

#include<stdio.h>

void swap(int* a, int* b) 
{
	int temp = *a;
	*a = *b;
	*b = temp;
}

int main(void)
{
	int a = 10;
	int b = 20;

	printf("%d\n", a);  //输出:10
	printf("%d\n", b); //输出:20

	//(地)址传递    形参可以改变实参的值
	swap(&a,&b);

	printf("%d\n", a); //输出:20
	printf("%d\n", b); //输出:10

	return 0;
}

程序原理解析如下:
image

posted @ 2021-07-22 15:40  言非  阅读(173)  评论(0编辑  收藏  举报