C++ Pointers are passed as arguments to functions

  • 2020-04-02 01:57:41
  • OfStack

Only in the called function, the pointer to the reference operation, can be reached without the return value, the pointer to the variable to make corresponding changes.

Here are two examples;

Requirements: define and initialize two string variables and perform output operations; Then call the function to make the value of the two variables exchange, and the call function to pass the value by passing the pointer to achieve.

Program 1.1

#include<iostream>
#include<string>
using namespace std;
int main(){
   string str1="I love China!",str2="I love JiNan!";
   void Exchange(string *p1,string *p2);
   cout<<"str1: "<<str1<<endl;
   cout<<"str2: "<<str2<<endl;
   Exchange(&str1,&str2);
   cout<<"str1: "<<str1<<endl;
   cout<<"str2: "<<str2<<endl; 
   return 0;
}
void Exchange(string *p1,string *p2){
 string *p3;
 p3=p1;
 p1=p2;
 p2=p3;
}

Output results:

< img Alt = "" border = 0 SRC =" / / img.jbzj.com/file_images/article/201310/2013101610295023.jpg ">

Program 1.2

#include<iostream>
#include<string>
using namespace std;
int main(){
   string str1="I love China!",str2="I love JiNan!";
   void Exchange(string *p1,string *p2);
   cout<<"str1: "<<str1<<endl;
   cout<<"str2: "<<str2<<endl;
   Exchange(&str1,&str2);
   cout<<"str1: "<<str1<<endl;
   cout<<"str2: "<<str2<<endl; 
   cout<<endl;
   return 0;
}
void Exchange(string *p1,string *p2){
 string p3;
 p3=*p1;
 *p1=*p2;
 *p2=p3;
}

Output results:

< img Alt = "" border = 0 SRC =" / / img.jbzj.com/file_images/article/201310/2013101610295024.jpg ">

Analysis:

By comparing the results of the two programs, the function in program 1.1 did not achieve the purpose of exchanging values, while program 1.2 did;

Because in the main function, the main function passes the address of the first element of str1 and str2 as an argument to the Exchange function; In the Exchange function, p1 is used to receive the address of str1, and p2 is used to receive the address of str2.

In program 1.1, only the values of pointer p1 and p2 are exchanged, with no effect on the original str1 and str2 strings. In program 1.2, it's *p1 and *p2 that are swapped, and *p1 is str1 itself, and *p2 is str2 itself, so it's actually str1 and str2 that are swapped


Related articles: