指针作为参数传递

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

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 @   He_LiangLiang  阅读(115)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
历史上的今天:
2020-08-29 centos中开启daytime服务
点击右上角即可分享
微信分享提示