C++ 指针(1)

本文详细解析了C++中指针的基本概念,包括&符号用于获取内存地址、*符号作为间接运算符的作用,以及通过示例程序展示了这两个操作符如何相互抵消。此外,还介绍了如何利用指针实现按引用传递,改变了传入参数的值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. 首先需要明白的便是&符号

   想完全弄明白的时候细究这篇博客。

    https://blog.youkuaiyun.com/msdnwolaile/article/details/50890365

  现在在指针的章节,我们要先知道&符号代表的是返回操作数的内存地址。

2. 符号 *

   “*”被叫做间接运算符,也可以叫间接引用。

    比如说 cout << *Ptr <<endl;

    代表的便是输出Ptr指针所指向的内存空间内所存储的数据。

3.以下为测试的一个小程序

#include<iostream>
using namespace std;

int main(){
   int a;
   int *ptr;
   
   a = 7;
   ptr = &a;
   
   cout << "The adress of a is" << &a
        << "\nThe vaule of ptr  is " << ptr;
 
   cout << "\n\nThe value of a is" << a
        << "\nThe value of *ptr is" << *ptr;

   cout<<"\nShow that * and & are inverses of "
       <<"\n*&ptr = "<<*&ptr
       <<"\n&*ptr = "<<&*ptr<<endl;
}

输出的结果则是

The adress of a is0x7ffd882dd9bc
The vaule of ptr  is 0x7ffd882dd9bc

The value of a is7
The value of *ptr is7
Show that * and & are inverses of
*&ptr = 0x7ffd882dd9bc
&*ptr = 0x7ffd882dd9bc
songsujing@songsujing-UX303LN:~/yuan$ gedit Ptr.cpp

 


从结果中可以看出一些东西,也能理解的更加深刻,值得注意的便是“&”“*”符号作用可以相互抵消。

4.接着使用指针的按引用传递方式

   接收地址实参的函数,必须定义指针参数来接收地址,并把该地址存储到对应的局部变量指针,要记住是没有返回值的。

#include<iostream>
using namespace std;

void cubeV(int *);

int main(){
 
    int a ;
    a = 5;
    cubeV(&a);  
    cout<<"the cube of a is "<<a;
}

void cubeV(int *Ptr){
    *Ptr = *Ptr * *Ptr * *Ptr;

}

运行的结果为

the cube of a is 125

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值