C語言進階:指針的進階(3)
數(shù)組傳參和指針傳參
實踐之中不免會碰到數(shù)組和指針作函數(shù)參數(shù)而如何設(shè)計形參的問題。
一維數(shù)組傳參
一維數(shù)組傳參,下列接收方式是否可行呢?
//1.
void test(int arr[])
{}
//2.
void test(int arr[10])
{}
//3.
void test(int* arr)
{}
int main()
{
int arr[10] = { 0 };
test(arr);
return 0;
}
1.數(shù)組傳參數(shù)組接收,可行但其實都會降級優(yōu)化成指針,編譯器不會真正創(chuàng)建一個數(shù)組。
2.由于形參數(shù)組形同虛設(shè),所以數(shù)組大小無意義,任意大小或無。(有歧義)
3.數(shù)組傳參本質(zhì)就是首元素地址,首元素類型為int,所以指針的類型為int*。
所以可以看出[]和*()是等價的。我愿稱之為*和[]的愛恨情仇?。ī\^▽^‐)
//1.
void test2(int* arr[2])
{}
//2.
void test2(int** arr)
{}
int main()
{
int* arr2[10] = { 0 };
test2(arr2);
return 0;
}
指針數(shù)組,每個元素類型為int*,故用二級指針接收數(shù)組名。
一維數(shù)組傳參,數(shù)組和指針接收。
二維數(shù)組傳參
//1.
void test(int arr[3][5])
{}
//2.
void test(int arr[][])
{}
//3.
void test(int arr[][5])
{}
int main() {
int arr[3][5] = { 0 };
test(arr);
}
- 二維數(shù)組傳參用二維數(shù)組接收,行可省略,但列不可以。
//4.
void test(int* arr)
{}
//5.
void test(int* arr[5])
{}
//6.
void test(int(*arr)[5])
{}
//7.
void test(int** arr)
{}
int main() {
int arr[3][5] = { 0 };
test(arr);
}
4.整型指針接收的應(yīng)該是整型變量的地址,而二維數(shù)組數(shù)組名為首行的數(shù)組地址。
5.指針數(shù)組和二維數(shù)組無關(guān)。
6.二維數(shù)組傳參用首行數(shù)組大小的數(shù)組指針接收。
7.二級指針和二維數(shù)組無關(guān)。
- 二維數(shù)組數(shù)組名
arr為首行“一維數(shù)組”的地址,數(shù)組的地址用數(shù)組指針接收。
int(*)[5]型數(shù)組指針指向元素個數(shù)為5的一維數(shù)組。指針+1訪問到下一行,每次跳一行。再解一層引用訪問一行里每個元素。
一級指針傳參
反向思考,若函數(shù)形參為指針,傳參時實參可以如何設(shè)計呢?
void test(int* ptr, int sz)
{}
void test(int arr[],int sz)
{}
int main()
{
//1.
int a = 10;
test(&a);
//2.
int arr[10] = { 0 };
test(arr);
return 0;
}
- 一級指針傳參,形參用指針和數(shù)組都行,但不提倡用一維數(shù)組。
- 若形參為指針,實參也可以是指針(地址),也可以是數(shù)組。
二級指針傳參
當二級指針作參數(shù)時,形參如何設(shè)計呢?
void test(int** pp) {
printf("%d\n", **pp);
}
void test(int* arr[]) {//用法不好
printf("%d\n", *arr[0]);
}
int main() {
int a = 10;
int* p = &a;
int** pp = &p;
test(pp);
return 0;
}
- 當二級指針作函數(shù)參數(shù)時,形參可以是二級指針和指針數(shù)組。
當形參為二級指針,實參可以傳什么呢?
void test(int** pp) {
printf("%d\n", **pp);
}
int main() {
int a = 10;
int* p = &a;
int** pp = &p;
int* arr[10] = { &a };
//1.
test(&p);
//2.
test(pp);
//3.
test(arr);
return 0;
}
- 當形參為二級指針時,實參可以是:二級指針(一級指針地址),指針數(shù)組首元素的地址。
總結(jié)
本篇文章就到這里了,希望能夠給你帶來幫助,也希望您能夠多多關(guān)注腳本之家的更多內(nèi)容!
相關(guān)文章
使用C語言實現(xiàn)珠璣妙算Mastermind小游戲
這篇文章主要介紹了使用C語言實現(xiàn)珠璣妙算Mastermind小游戲,這是一款益智類多人游戲游戲,非常有趣,需要的朋友可以參考下2023-03-03
C語言數(shù)據(jù)結(jié)構(gòu)之模式匹配字符串定位問題
這篇文章主要介紹了C語言數(shù)據(jù)結(jié)構(gòu)之模式匹配字符串定位問題的相關(guān)資料,希望通過本文能幫助到大家,讓大家理解這部分內(nèi)容,需要的朋友可以參考下2017-10-10
C程序函數(shù)調(diào)用&系統(tǒng)調(diào)用
這篇文章主要介紹了C程序函數(shù)調(diào)用&系統(tǒng)調(diào)用,需要的朋友可以參考下2016-09-09
Matlab實現(xiàn)數(shù)據(jù)的動態(tài)顯示方法
這篇文章主要為大家詳細介紹了Matlab使用Plot函數(shù)實現(xiàn)數(shù)據(jù)動態(tài)顯示方法,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-06-06

