QingfengLee
1/20/2016 - 11:15 AM

C++指针使用练习

C++指针使用练习

#include <tr1/unordered_map>
#include <iostream>
#include <string>

int main()
{
    int ** in = new int*[3]();
    in[0] = new int(1);
    in[1] = new int(2);
    in[2] = new int(3);
    
    std::cout << "address 1:" << in[0] << std::endl; //int 1 所在地址
    std::cout << "address 2:" << in[1] << std::endl; //int 2 所在地址
    std::cout << "address 3:" << in[2] << std::endl; //int 3 所在地址

    std::tr1::unordered_map<std::string,int**> dict;
    dict.insert({"0",&in[0]});     
    dict.insert({"1",&in[1]});
    dict.insert({"2",&in[2]});
    std::cout << "pointer address 1:" << dict["0"] << std::endl; //指向 int 1 所在地址的地址
    std::cout << "pointer address 2:" << dict["1"] << std::endl; //指向 int 2 所在地址的地址
    std::cout << "pointer address 3:" << dict["2"] << std::endl; //指向 int 3 所在地址的地址
    
    delete [] in;

    std::cout << "pointer address 1 (del):" << dict["0"] << std::endl; //指向 int 1 所在地址的地址
    std::cout << "pointer address 2 (del):" << dict["1"] << std::endl; //指向 int 2 所在地址的地址
    std::cout << "pointer address 3 (del):" << dict["2"] << std::endl; //指向 int 3 所在地址的地址
    
    //std::cout << *(dict["0"]) << std::endl; //该处内容被释放掉了
    //std::cout << *(dict["1"]) << std::endl; //该处内容被释放掉了
    //std::cout << *(dict["2"]) << std::endl; //该处内容被释放掉了
    
    //std::cout << **(dict["0"]) << std::endl; //中间的地址内容被删掉了,无法再 **
    //std::cout << **(dict["1"]) << std::endl; //中间的地址内容被删掉了,无法再 **
    //std::cout << **(dict["2"]) << std::endl; //中间的地址内容被删掉了,无法再 **
    return 0;
}