C++之指针_2

本文详细介绍了C++中的指针概念,包括指针、数组的关系,指针算术,数组名与指针的等价性,以及字符串与指针的交互。重点讨论了指针声明、赋值、解引用,以及数组名视为首元素地址的特性。同时,通过示例展示了如何使用指针进行动态和静态联编,以及如何安全地复制字符串到数组中。
摘要由CSDN通过智能技术生成

指针、数组和指针运算

指针和数组基本等价的原因在于指针算术( pointer arithmetic)和C++内部处理数组的方式。首先,我们来看一看算术。将整数变量加1后,其值将增加1;但将指针变量加1后,增加的量等于它指向的类型的字节数。将指向 double的指针加1后,如果系统对 double使用8个字节存储,则数值将增加8:将指向short的指针加1后,如果系统对 short使用2个字节存储,则指针值将增加2。下面程序演示了这种令人吃惊的现象,它还说明了另一点:C++将数组名解释为地址。

// addpntrs.cpp
#include <iostream>
int main()
{
    using namespace std;
    double wages[3] = {10000.0, 20000.0, 30000.0};
    short stacks[3] = {3,2,1};
    double* pw = wages;
    short* ps = &stacks[0];
    cout << "pw = " << pw <<", *pw = " << *pw <<endl;
    cout << "add 1 to the pw pointer:\n";
    pw = pw + 1;
    cout << "pw = " << pw <<", *pw = " << *pw <<"\n\n";
    cout << "ps = " << ps << ", *ps = "<<endl;
    cout << "add 1 to the ps pointer:\n"
    ps = ps + 1;
    cout << "ps = " << ps <<", *ps = " << *pw <<"\n\n";

    cout << "access two elements with array notation\n";
    cout << "stacks[0]= " << stacks[0] << ", stacks[1] = " << stacks[1] << endl;
    cout << "access two elements with pointer notation\n";
    cout << "*stacks= " << *stacks << ", stacks[1] = " << *(stacks+1) << endl;



}

//程序输出
pw = 0x28ccf0,*pw = 10000
add 1 to the pw pointer:
pw = ox28ccf8,*pw = 20000


ps = ox28ccea,*ps = 3
add 1 to the ps pointer:
ps = ox28ccec,*ps = 2

access two elements with array notation
stacks[0] = 3, stacks[1] = 2
access two elements with pointer notation
*stacks = 3, *(stacks+1) = 2

在多数情况下,C++将数组名解释为数组第1个元素的地址。因此,下面的语句将pw声名为指向double类型的指针,然后将它初始化为wages数组中的第1个元素的地址:

double * pw = wages;

和所有数组一样,wages也存在下面的等式:
wages = &wages[0] = address of first element of array

接下来,程序查看pw和 ∗ * pw的值,前者是地址,后者是存储在该地址中的值。由于pw指向第1个元素,因此 ∗ *

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值