1. 程式人生 > >C語言函式之輸入引數

C語言函式之輸入引數

輸入引數:承上啟下的作用

呼叫者:函式名(要傳遞的資料)            //實參

被調者:函式的具體實現

函式的返回值 函式名(接收的資料)      //形參

。。。。

實參 傳遞給 形參

傳遞形式:逐一拷貝

值傳遞典型錯誤:

#include<stdio.h>
void swap(int a,int b)
{
	int c;
	c = a;
	a = b;
	b = c;
}
int main()
{
	int a = 10;
	int b = 20;
	printf("the value of a is %d,b is %d\n",a,b);
	swap(a,b);
	printf("After swap,the value of a is %d,b is %d\n",a,b);
}

執行結果:
[email protected]
:~$ gcc -o swap swap.c [email protected]:~$ ./swap the value of a is 10,b is 20 After swap,the value of a is 10,b is 20

 解決辦法:地址傳遞

地址傳遞用途:

1、上層(呼叫者)讓下層(子函式)修改自己的空間值的方式;

2、類似結構體這樣的空間,函式與函式之間呼叫關係。

#include<stdio.h>
void swap(int *a,int *b)
{
	int c;
	 c = *a;
	*a = *b;
	*b = c;
}
int main()
{
	int a = 10;
	int b = 20;
	printf("the value of a is %d,b is %d\n",a,b);
	swap(&a,&b);
	printf("After swap,the value of a is %d,b is %d\n",a,b);
}
結果:
[email protected]
:~$ gcc -o swap swap.c [email protected]:~$ ./swap the value of a is 10,b is 20 After swap,the value of a is 20,b is 10

連續空間的傳遞:陣列、結構體

1、陣列

陣列名---標籤

2、機構體

結構體變數:

struct abc{int a;int b;int c;};

struct abc buf;