C++基础教程(四)——指针(3)

//=====================================================
// Name        : Pointer1.cpp
// Author      : lf
// Version     : 《C++语言基础教程》 吕凤翥 P41——P45 2.5.2
// Description : 指针数组和指向数组的指针以及字符指针
//=====================================================

#include <iostream>
using namespace std;

int main() {
	cout<<"<----指针小复习---->"<<endl;
	int a=5;
	int *pa=&a;
	cout <<"取出指针里面保存的地址的方式:pa="<<pa<<endl;
	cout <<"取出指针里面保存的地址所表示的值的方式:*pa="<<*pa<<endl;
	cout<<"--------------------------"<<endl;

	cout<<"<----指针数组---->"<<endl;
	int b[3]={1,2,3};
	int *pb[]={&b[0],&b[1],&b[2]};
	//*pb指向了数组的第一个元素即&b[0],这是一个地址
	//**pb表示将该地址对应的值取出.以下类似
	cout<<"**pb="<<**pb<<endl;
	cout<<"*(*pb+1)="<<*(*pb+1)<<endl;
	cout<<"*(*pb+2)="<<*(*pb+2)<<endl;
    cout<<"--------------------------"<<endl;

    int c[3]={1,2,3};
    int *pc[3];
    pc[0]=&c[0];
    pc[1]=&c[1];
    cout<<"<----C++规定:任何数组的数组名都是一个常量指针,其值是该数组首元素的地址值---->"<<endl;
    cout<<"<----所以:c+2表示c[2]的地址---->"<<endl;
    *(pc+2)=c+2;
    cout<<"*pc[0]="<<*pc[0]<<",**(pc+1)="<<**(pc+1)<<",*pc[2]="<<*pc[2]<<endl;
    cout<<"--------------------------"<<endl;

    cout<<"<----指向数组的指针---->"<<endl;
    int d[2][3]={1,2,3,4,5,6};
    int (*pd)[3];
    cout<<"<----C++规定:任何数组的数组名都是一个常量指针,其值是该数组首元素的地址值---->"<<endl;
    cout<<"<----所以:pd=d+1表示pd指向了数组d的第1行(行数从0开始)---->"<<endl;
    cout<<"<----这样就可以用pd表示数组d的各元素值,比如pd[0][0]表示d[1][0]---->"<<endl;
    cout<<"<----关于该示例,需要进一步探讨.请参见书本P42---->"<<endl;
    pd=d+1;
    cout<<"pd[0][1]="<<pd[0][1]<<endl;
    cout<<"pd[-1][0]="<<pd[-1][0]<<endl;
    cout<<"pd[0][0]="<<pd[0][0]<<endl;
    cout<<"*(*pd+2)="<<*(*pd+2)<<endl;
    cout<<"--------------------------"<<endl;


    cout<<"<----字符指针---->"<<endl;
    cout<<"<----字符指针是指向字符串的指针---->"<<endl;
    char *p,s1[10],s2[10];
    p="teacher";
    for(int i=0;i<7;i++){
    	s1[i]=*p++ +1;
    }
    s1[7]='\0';
    cout<<"s1="<<s1<<endl;

    for(int i=0;i<7;i++){
       	s2[i]=*(s1+i)-1;
     }
    s2[7]='\0';
    cout<<"s2="<<s2<<endl;
    cout<<"--------------------------"<<endl;

    cout<<"<----字符指针数组---->"<<endl;
    cout<<"<----字符指针数组是指元素为字符指针的数组---->"<<endl;
    char *s[3]={"char","long","int"};
    s[0]="double";
    *(s+1)="float";
    cout<<"s[0]="<<s[0]<<endl;
    cout<<"*(s+1)="<<*(s+1)<<endl;
    cout<<"s[2]="<<s[2]<<endl;
    cout<<"*(*s+2)="<<*(*s+2)<<",*(s[2]+1)="<<*(s[2]+1)<<endl;
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

谷哥的小弟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值