C + + pointer type function

Time:2022-5-4

The following essay will describe the functions of C + + pointer type.

Original link: https://www.cnblogs.com/iFrank/p/14444379.html

Pointer type function

If the return value of a function is a pointer, the function is a pointer type function.

   Definition form of pointer function

Storage type * data type * function name () 
  {// function body statement
  }

批注 2020-03-04 221235.png

1 example of error
 2 
 3 int main(){
 4     int* function();
 5     int* ptr= function();
 6     *prt=5; // Dangerous access!
 7     return 0;
 8 }
 9 int* function(){
10     int local=0; // The scope and lifetime of non-static local variables are limited to the body of this function
11     return &local;
12} // at the end of the function, the variable local is released
1 correct example 1
 2 
 3 #include
 4 using namespace std;
 5 int main(){
 6     int array[10]; // Array defined in main function
 7     int* search(int* a, int num);
 8     for(int i=0; i<10; i++)
 9       cin>>array[i];
10     int* zeroptr= search(array, 10);  // Pass the first address of the array in the main function to the sub function
11     return 0;
12 }
13 int * search (int * a, int Num) {// pointer a points to the array defined in the main function
14     for(int i=0; i
1 correct example 2
 2 
 3 #includeusing namespace std;
 4 int main(){
 5     int* newintvar();
 6     int* intptr= newintvar();
 7     *intptr=5; // The address accessed is legal and valid
 8     delete intptr; // If you forget to release it here, it will cause memory leakage
 9     return 0;
10 }
11 int* newintvar (){ 
12     int* p=new int();
13     return p; // The returned address points to the dynamically allocated space
14} // at the end of the function, the address in P is still valid
15

 

 

Recommended Today

Golang influxdb basic operation

Infixdb basic operation Basic operation connect [[email protected] ~]# influx -precision rfc3339 Connected to http://localhost:8086 version 1.8.0 InfluxDB shell version: 1.8.0 > precisionThe parameter indicates the format and precision of any returned timestamp. In the above example,rfc3339Yes, let influxdb returnRFC339Timestamp of format (yyyy-mm-ddthh: mm: SS. Nnnnnnnz). validate logon > auth username: icms password: [email protected] Operation database […]