三、指针与数组和函数
3.1 指针与数组
利用指针访问数组中的一个数据
int arr[10] = {0,1,2,3,4,5,6,7,8,9};
int * p = arr;//arr即是数组的首地址
cout <<"数组中的第一个元素是:"<< *p << endl;
p++; //指针向后移动4个字节,即为第二个元素首地址
cout <<"数组中的第二个元素是:"<< *p << endl;
利用指针访问数组中的每一个数据
int * p2 = arr;
for(int i = 0; i < 10; i++)
{
cout << *p2 <<" ";
p2++
}
cout << endl;
3.2 指针与函数
函数的值传递不能改变实参的值,但是地址传递可以修改实参的值
//值传递
viod swap01(int a,int b)
{
int temp = 0;
a = b;
b = temp;
cout << "swap01 a = " << a << endl;
cout << "swap01 b = " << b << endl;
}
//地址传递
viod swap02(int *p1,int *p2)
{
int temp = 0;
*p1 = *p2;
*p2 = temp;
cout << "swap01 *p1 = " << *p1 << endl;
cout << "swap01 *p2 = " << *p2 << endl;
}
int main()
{
int a = 10;
int b = 20;
//值传递
//swap01(a,b);
//cout << "a = " << a << endl;
//cout << "b = " << b << endl;
//地址传递
swap02(&a,&b);
cout << "a = " << a << endl;
cout << "b = " << b << endl;
return 0;
}
综合案例:对一个数组进行冒泡排序
void bubbleS(int * arr, int len)
{
for (int i = 0; i < len-1; i++)
{
for (int j = 0; j < len-1-i; j++)
{
if (arr[j] > arr[j+1])
{
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
viod printArray(int * arr,int len)
{
for (int i = 0; i < len; i++)
{
cout << arr[i]<<" ";
cout << endl;
}
}
int main()
{
int arr[10] = {4,3,6,9,1,2,10,8,7,5};
int len = sizeof(arr)/sizeof(arr[0]);
//冒泡排序
bubbleSort(arr,len);
//打印结果
printArray(arr,len)
return 0;
}