关于指针的引用或者二级指针

#include <iostream>

const int MAXSIZE = 10;

void arrSetZero(int *arr,int size){
    for(int i=0;i<size;i++){
        arr[i] = 0;
    }
}

void arrDealWithoutNew(int *arr,int size){
    for(int i=0;i<size;i++){
        arr[i] = 10-i;
    }
}

int* arrDealWithNewBase(int *arr,int size){
    arr = new int[MAXSIZE];
    for(int i=0;i<size;i++){
        arr[i] = i;
    }
    return arr;
}

//意图修改地址,用地址的引用
void arrDealWithNewRef(int *&arr,int size){
    delete arr;
    arr = nullptr;
    arr = new int[MAXSIZE];
    for(int i=0;i<size;i++){
        arr[i] = i;
    }
}

//意图修改地址,用地址的地址(二级指针)
void arrDealWithNewPP(int **arr,int size){
    delete *arr;
    *arr = nullptr;
    *arr = new int[MAXSIZE];
    for(int i=0;i<size;i++){
        (*arr)[i] = 0;
    }
}


void arrShow(int *arr,int size){
    for(int i=0;i<size;i++){
        std::cout<<arr[i]<<" ";
    }
    std::cout<<std::endl;
}

int main(){

    int *arr = new int[MAXSIZE];
    std::cout<<"arrSetZero:"<<std::endl;
    arrSetZero(arr,MAXSIZE);
    std::cout<<"The addr:\t"<<arr<<std::endl;
    arrShow(arr,MAXSIZE);

    std::cout<<"arrDealWithNewBase:"<<std::endl;
    int  *p = arrDealWithNewBase(arr,MAXSIZE);
    std::cout<<"In Function Addr:"<<p<<std::endl;
    std::cout<<"The addr:\t"<<arr<<std::endl;
    arrShow(arr,MAXSIZE);
    delete p;
    p = nullptr;

    std::cout<<"arrDealWithoutNew:"<<std::endl;
    arrDealWithoutNew(arr,MAXSIZE);
    std::cout<<"The addr:\t"<<arr<<std::endl;
    arrShow(arr,MAXSIZE);

    std::cout<<"arrDealWithNewRef:"<<std::endl;
    arrDealWithNewRef(arr,MAXSIZE);
    std::cout<<"The addr:\t"<<arr<<std::endl;
    arrShow(arr,MAXSIZE);

    std::cout<<"arrDealWithNewPP:"<<std::endl;
    arrDealWithNewPP(&arr,MAXSIZE);
    std::cout<<"The addr:\t"<<arr<<std::endl;
    arrShow(arr,MAXSIZE);

    delete arr;
    arr = nullptr;

    return 0;
}

posted on 2018-08-17 09:56  jyunlon  阅读(649)  评论(0编辑  收藏  举报

导航