C++学习 --- 函数、指针和数组

1、指针操作数组

#include <iostream>
using namespace std;
​
int main(){
    int arr[10] = {1,2,3,4,5,6,7,8,9,10};
    cout << "The first element is:" << arr[0] << endl;
    int *p = arr;//arr is the first address of the array
    cout << "Use the pointer to access the first element:" << *p << endl;
    p++;
    cout << "Use the pointer to access the second element:" << *p << endl;
    //Use pointers to traverse the array
    int * p2 = arr;
    for(int i = 0;i < 10 ;i++){
        //cout << arr[i] << " ";
        cout << *p2++ << " ";
        //p2++;
    }
    cout << endl;
    return 0;
}

  

2、函数的地址传递,指针作为函数参数

总结:如果不想修改实参,就用值传递,如果想修改实参,就用地址传递。灵活使用。

#include <iostream>
using namespace std;
​
​
//实现两个数字进行交换
//值传递
void swap01(int a,int b){
    int temp = a;
    a = b;
    b = temp;
    cout << "a = " << a << endl;
    cout << "b = " << b << endl;
}
//地址传递
void swap02(int *p1,int *p2){
    int temp = *p1;
    *p1 = *p2;
    *p2 = temp;
    //cout << "*p1 = " << *p1 << endl;
    //cout << "*p2 = " << *p2 << endl;
}
int main(){
    int a = 10;
    int b = 20;
    cout << "Before the exchange" << endl;
    cout << "a = " << a << endl;
    cout << "b = " << b << endl;
    //值传递
    //swap01(a,b);
    //地址传递
    swap02(&a,&b);
    cout << "After the exchange" << endl;
    cout << "a = " << a << endl;
    cout << "b = " << b << endl;
    
    return 0;
}

  

3.指针数组和函数

#include <iostream>
using namespace std;
​
/** 实现:封装一个函数,利用冒泡排序,实现对整型数组的升序排序。
 ** int arr[10] = {4,3,6,9,1,2,10,8,7,5};
**/ ​ //冒泡排序,参数1:数组的首地址 参数2:数组的长度 void bubbleSort(int * arr,int len){ for(int i = 0;i < len -1;i++){ for(int j = 0;j < len -i -1;j++){ if(arr[j] > arr[j+1]){ int temp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = temp; } } } } ​ //打印数组 printArray(int * arr,int len){ for(int i = 0;i < len;i++){ cout << arr[i] << " "; } cout << endl; } ​ int main(){ //1.先创建一个数组 int arr[10] = {4,3,6,9,1,2,10,8,7,5}; int len = sizeof(arr)/sizeof(arr[0]); //2.创建一个函数实现冒泡排序 bubbleSort(arr,len); //3.打印排序后的数组 printArray(arr,len); return 0; } ​ //函数传递数组长度是为了让程序更加健壮灵活

  

 

posted @ 2021-08-02 15:45  yiwenzhang  阅读(64)  评论(0编辑  收藏  举报