《C++捷径教程》读书笔记--Chapter 6--指针(第二部分)

这是《C++捷径教程》第六章指针部分的读书笔记,包含多个C++程序示例,如指针与字符串字面量、指针比较运算、指针数组、多重间接用法等,还展示了错误程序示例,帮助理解指针在C++中的应用。

//--《C++捷径教程》读书笔记--Chapter 6--指针(第二部分)
//--读书笔记--Chapter 6--指针
//--11/13/2005 Sun.
//--Computer Lab
//--Liwei

//--程序#8  指针与字符串字面量

#include <iostream>
using namespace std;

int main()
{
    char *s;
 s="Pointer are fun to use./n";
 cout<<s;

    return 0;
}

//--程序#9  一个指针比较运算的例子

#include <iostream>
using namespace std;

int main()
{
    int num[10];
 int *start,*end;

 //start=num;//
 start=&num[0];
 //end=&num[9];//
 end=start+9;

 while(start<=end)
 {
     cout<<"Enter a number: ";
  cin>>*start++;
 }

 start=num;

 while(start<=end)
 {
     cout<<*start++<<' ';
 }
    cout<<endl;

    return 0;
}


//--程序#10  一个指针数组的例子

#include <iostream>
#include <cstdlib>
#include <conio.h>
using namespace std;

char *fortunes[]={
    "Soon,you will come into some money./n",
 "A new love will enter your life./n",
    "You will live long and prosper./n",
    "Now is a good time to invest for the future./n",
    "A close friend will ask for a favor./n"
};

int main()
{
    int chance;
 cout<<"To see your fortune,press a key: ";
 
 while(!kbhit()) chance=rand();
    cout<<endl;

    //chance=rand();
 chance=chance&5;
 
 cout<<fortunes[chance];

 cout<<endl;
    getchar();
    return 0;
}

//--程序#11  一个指针数组的例子

#include <iostream>
#include <cstdlib>
#include <conio.h>
using namespace std;

char *keyword[][2]={
    "for","for for for",
 "if","if if if",
    "switch","switch switch switch",
    "while","while while while",
    "/0",""
};

int main()
{
    char str[80];
    int i;
 
 cout<<"Enter keyword: ";
 cin>>str;

 for(i=0; *keyword[i][1]; i++)
  if( !strcmp(keyword[i][0],str) )
   cout<<keyword[i][1];
   
 cout<<endl<<"======="<<endl;
    return 0;
}


//--程序#12  说明多重间接的用法

#include <iostream>
using namespace std;

int main()
{
    int x,*p,**q;
 x=10;
 p=&x;
 q=&p;
 cout<<x<<' '<<*p<<' '<<**q<<endl;

 cout<<endl<<"======="<<endl;
    return 0;
}


//--程序#13  错误的程序

#include <iostream>
using namespace std;

int main()
{
    int x,*p;
 x=10;
 *p=x;//p未初始化

 cout<<x<<' '<<*p;

 cout<<endl<<"======="<<endl;
    return 0;
}

//--程序#14  忘记复位指针的程序

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;

int main()
{
    char s[80];
 char *pl;
 //pl=s;

 do{
     pl=s;
  cout<<"Enter a string: ";
  gets(pl);
  while(*pl)
   cout<<(int)*pl++<<' ';
  cout<<endl;
 }while(strcmp(s,"done"));

 cout<<endl<<"======="<<endl;
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值