指针作为参数传递

指针作为参数传递的时候,需要用指针的指针 作为参数

eg:

 1 #include <iostream>
 2 using namespace std;
 3 
 4 int* p;
 5 void func(int** a){
 6     *a = new int(5);
 7 }
 8 
 9 int main()
10 {
11     p= nullptr;
12     func(&p);  //指针作为参数传递的时候,必须传入指针的指针
13     cout<<"p:"<<p <<",*p:"<<*p<<endl;
14     return 0;
15 }

 

 

 1 //函数参数传递的只能是数值,所以当指针作为函数参数传递时,传递的是指针的值,而不是地址。
 2 
 3 #include <iostream>
 4 using namespace std;
 5 
 6 void pointer(int *p)
 7 {
 8     int a = 11;
 9     cout<<"Enter function"<<endl; 
10     cout<<"the p is point to "<<p<<",addr is "<<&p<<",*p is "<<*p<<endl;
11     
12     *p = 11;
13     cout<<"the p is point to "<<p<<",addr is "<<&p<<",*p is "<<*p<<endl;
14 
15     p = &a;
16     cout<<"the p is point to "<<p<<",addr is "<<&p<<",*p is "<<*p<<endl;
17 
18     cout <<"function return"<<endl;
19 }
20 
21 int main()
22 {
23     int b = 22;
24     int * p = &b;
25     cout <<"the b address is " <<&b<<endl;
26     cout<<"the p is point to "<<p<<",addr is "<<&p<<",*p is "<<*p<<endl;
27     pointer(p);
28     cout<<"the p is point to "<<p<<",addr is "<<&p<<",*p is "<<*p<<endl;
29 
30     return 0;
31 }
32 
33 //===================== 输出  ===================================
34 the b address is 0x7ffc38a7b8cc
35 the p is point to 0x7ffc38a7b8cc,addr is 0x7ffc38a7b8c0,*p is 22
36 Enter function
37 the p is point to 0x7ffc38a7b8cc,addr is 0x7ffc38a7b898,*p is 22
38 the p is point to 0x7ffc38a7b8cc,addr is 0x7ffc38a7b898,*p is 11
39 the p is point to 0x7ffc38a7b8ac,addr is 0x7ffc38a7b898,*p is 11
40 function return
41 the p is point to 0x7ffc38a7b8cc,addr is 0x7ffc38a7b8c0,*p is 11
42 
43 /////////// 解释 ///////////
44 指针的值,指针的地址,指针指向地址的值

 

错误的用法

#include <stdio.h>
#include <stdlib.h>  // malloc
#include <string.h>  // strcpy

void GetMemory(char *p,int num)  //错误的用法
{
    p=(char*)malloc(sizeof(char)*num); 
}

int main()
{
    char *str=NULL;
    GetMemory(str,100); 
    strcpy(str,"hello \r\n");
    printf(str);

    return 0;
}

 

 

正确的用法

 1 #include <stdio.h>
 2 #include <stdlib.h>  // malloc
 3 #include <string.h>  // strcpy
 4 
 5 void GetMemory(char **p,int num)
 6 {
 7     *p=(char*)malloc(sizeof(char)*num); 
 8 }
 9 
10 int main()
11 {
12     char *str=NULL;
13     GetMemory(&str,100); 
14     strcpy(str,"hello \r\n");
15     printf(str);
16 
17     return 0;
18 }

 

posted @ 2022-08-29 22:15  He_LiangLiang  阅读(130)  评论(0)    收藏  举报