C++ 中指標,指標的引用,指標的指標的區別

來源:互聯網
上載者:User
c++中指標,指標的引用,指標的指標的區別看例子和結果:

#include "stdafx.h"
#include <iostream>
using namespace std;
void FreePtr1(int* ptr1)
{
    delete ptr1; 
    ptr1 = NULL;
}

void FreePtr2(int*& ptr2)
{
    delete ptr2; 
    ptr2 = NULL;

void FreePtr3(int **ptr3)
{
    delete *ptr3;
    *ptr3 = NULL;
}

void main()
{
    cout<<"---------------------------------------"<<endl;
    int *p1 = new int;
    *p1 = 1;
    cout<<"*p1="<<*p1<<endl;
    FreePtr1(p1);
    cout<<"after call freePtr1"<<endl;
    if(p1 != NULL)
    {
        cout<<"p1 is not null"<<endl;
        cout<<"*p1="<<(*p1)<<endl;
    }
    cout<<"---------------------------------------"<<endl;
    int *p2 = new int;
    *p2 = 2;
    cout<<"*p2="<<*p2<<endl;
    FreePtr2(p2);
    cout<<"after call freePtr2"<<endl;
    if(p2 != NULL)
    {       
        cout<<"*p2="<<*p2<<endl;
    }
    else
    {
        cout<<"the p2 is null"<<endl;
    }
    cout<<"---------------------------------------"<<endl;
    int *p3 ;
    p3 = new int(3);
    cout<<"*p3="<<*p3<<endl;
    FreePtr3(&p3);
    cout<<"after call freePtr3"<<endl;
    if(p3 != NULL)
    {       
        cout<<"*p3="<<*p3<<endl;
    }
    else
    {
        cout<<"the p3 is null"<<endl;
    }
    cout<<"---------------------------------------"<<endl;
    system("pause");

}

結果:

comments:

對p1指標:
cout<<"---------------------------------------"<<endl;
 int *p1 = new int;
 *p1 = 1;
 cout<<"*p1="<<*p1<<endl;

// FreePtr1(p1);
void FreePtr1(int* ptr1)
{

 delete ptr1; 

 ptr1 = NULL;

}

 cout<<"after call freePtr1"<<endl;
 if(p1 != NULL)
 {
  cout<<"p1 is not null"<<endl;
  cout<<"*p1="<<(*p1)<<endl;
 }
 cout<<"---------------------------------------"<<endl;

而p2為:
調用前:

調用後:

注意:函數的參數進行值拷貝,即使傳的是指標,也的對指標(即指標裡存的地址)的拷貝, 可不是指標裡地址所指的值的拷貝啊! 原文地址

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.