C++基礎 數組(二)

參考

C++ Primer Plus (第6版)

函數與數組

數組作爲函數參數

數組作爲形參
#include <iostream>

using namespace std;

/*
	n爲數組的長度,sizeof 一個指針 是得不到數組的長度, 需要傳入數組的長度
*/
int sum_arr(int arr[], int n) 
{
	int total = 0;
	for (int i = 0; i < n; i++)
	{
		total += arr[i];
	}
	return total;
}

int main()
{
	int cookies[8] = { 1,2,4,8,16,32,64,128 };
	cout << sum_arr(cookies, 8) << endl; // 255

	system("pause");
	return 0;
}

在c++規則中,cookies是其第一個元素的地址,也就是在

	sum_arr(cookies, 8)

第一個參數傳入的參數是一個數組的地址,那麼這表明正確寫法應該是

	int sum_arr(int* arr, int n)

在c++中,當且僅當用於函數頭或函數原型中,int *arr 和 int arr[] 的含義相同,都是指向一個int指針(java不同,且定義數組不要和c++弄混)

數組名和指針對應好處: 作爲參數,可以節省複製整個數組的時間和內存
數組名和指針對應壞處: 原始數據會被破壞,用const防止破壞

	
void show_array(double* arr, int n)
{
	arr[0] += 10;
}

int main()
{
	double constArray[2] = { 12,13 };
	show_array(constArray, 2);
	for (int i = 0; i < 2; i++)
	{
		cout << constArray[i] << endl; // 22,13
	}
}

用const ,如果對數組進行修改操作,編譯器會禁止這麼做
在這裏插入圖片描述
不需要傳入數組長度,也就是把數組起始地址和結束地址爲參數傳入函數

#include <iostream>

using namespace std;

int sum_arr(const int* begin, const int* end)
{
	const int* ptr = begin;
	int total = 0;
	for (; ptr != end; ptr++)
	{
		total += *ptr;
	}
	return total;
}

int main()
{
	
	int cookies[8] = { 1,2,4,8,16,32,64,128 };
	cout << sum_arr(cookies, cookies + 8) << endl; // 255
	
	system("pause");
	return 0;
}

數組爲二維數組
跟一維數組同理,參數也就是指針指向數組
在c++中,當且僅當用於函數頭或函數原型中,int (arr)[i] 和 int arr[][i] 的含義相同,都是指向一個int[i]指針,不要忘記給arr加上括號,不然就是i個指向int的指針

#include <iostream>

using namespace std;

int sum(int(*ar2)[4], int size)
{
	int total = 0;
	for (int i = 0; i < size; i++)
	{
		for (int j = 0; j < 4; j++)
		{
			total += ar2[i][j];
		}
	}
	return total;
}

int sum2(int ar2[][4], int size)
{
	int total = 0;
	for (int i = 0; i < size; i++)
	{
		for (int j = 0; j < 4; j++)
		{
			total += ar2[i][j];
		}
	}
	return total;
}

int main()
{
	int data[3][4] = { {1,2,3,4},{5,6,7,8},{2,4,5,6} };

	cout << sum(data, 3) << endl;	// 53
	cout << sum2(data, 3) << endl;	// 53
	
	system("pause");
	return 0;
}

數組作爲函數的返回值

返回值也就是指針,推薦參數引用
不然容易出現問題,比如
在函數內定義靜態數組,出了函數,return的指針就釋放了

上一篇:c++基礎 數組(一)
下一篇:c++基礎 數組(三)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章