Introduction to C + + Classic-Example 5.19-reference and passing parameters of pointers

Source: Internet
Author: User

1: Reference passing parameters and pointer passing parameters can achieve the same purpose. Pointer passing parameters also belong to a value pass, which passes a copy of the pointer variable. If you use a pointer reference, you can achieve the purpose of changing the pointer address within the function body. Run the code as follows:

//5.19.cpp: Defines the entry point of the console application. //#include"stdafx.h"#include<iostream>usingstd::cout;usingStd::endl;Static int Global= -;//Static global Variables voidGetmax (int* &p)//reference to Pointers{    if(*p<Global)    {        DeleteP//frees memory. p = &Global;//the equivalent of PI1 's reference changed.    }} voidGetmin (int*p) {    if(*p>Global)    {        DeleteP//freed up the memory that pI2 points top = &Global;//copy value changed, pI2 no change    }}intMain () {int* PI1 =New int;//dynamically assign an address    int* PI2 =New int; cout<<"pI1 point to Address:"<<pI1<<Endl; cout<<"pI2 point to Address:"<<pI2<<Endl; *PI1 = the;//Global Larger*pi2 = -;//Global Smallercout<<"global variable Address:"<<&Global<<Endl; cout<<"bring pI1 and pI2 into the Getmax and getmin functions respectively"<<Endl;    Getmax (pI1);    Getmin (pI2); cout<<"pI1 point to Address:"<<pI1<<Endl; cout<<"pI2 point to Address:"<<pI2<<Endl; cout<<"value of *pi1:"<<*pI1<<Endl; cout<<"value of *pi2:"<<*pI2<<Endl; return 0;}/*The Getmax function changes the address of the pointer by passing a reference to the pointer, and the address of the pointer pI1 finally points to the global variable. The Getmin function, which passes pointers by value, can only change the contents of memory, and performing operations on memory does not change the address pointed to by the pointer. */
View Code

Operation Result:

Introduction to C + + Classic-Example 5.19-reference and passing parameters of pointers

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.