深入理解字符串、数组、指针---联系与应用

        字符串是存储在内存的连续字节中的一系列字符。C++处理字符串有两种方式,第一中来自C语言,第二种是基于string类库的方法。

         在此我们先介绍第一种方式,即把字符串存储在char型数组中,其中每个字符都位于自己的素组元素中。代码如下:

char str1[5] = {'a','b','c','d','\0'}; //  \0为空字符(其ASCLL码为0)

      第二种方式,字符串常量(string constant)或字符串字面值(string liteal)代码如下

char str2[] = "abcd"; // the \0 is understand; let the compiler count the size
 

 注意这种定义方式是错误的   

//因为 这是定义了一个字符型的指针, 它只会只想一个字符的存储位置        char *str="hello" 

    下面在给大家介绍一种存储多个字符串的方式——指针数组。定义方式如下:

 

    char* pstr [] = {"Robert Redford",  // 注意:数组中存放的是这一个字符串的首地址,一下程序会测试这一结果
               "Hopalong Cassidy",
      "Lassie",
      "Slim Pickens",
      "Boris Karloff",
      "Oliver Hardy"
 }

 

下面用一个最简单的典型的幸运之星程序 使用和验证以上结论,源代码如下:

#include <iostream>
#include <stdio.h>
using std::cin;
using std::cout;
using std::endl;

int main ()
{
 char* pstr [] = {"Robert Redford",
               "Hopalong Cassidy",
      "Lassie",
      "Slim Pickens",
      "Boris Karloff",
      "Oliver Hardy"
 };
 char* pstart ("Your lucky star is");
 int dice (0);
 char str1[]="abcdefig";
 char* str2 = "abcdefig";//
 //The follwing code is used for comprehending string  constant and array of strings.
 cout << "The length of  Strings is:"<< strlen(str1) <<endl
  << "The size of the array of string is:" << sizeof str1
  << endl;
 cout << "The size of the str2 is:" << sizeof str2
  << endl <<"指针指向的元素为:"<< *str2 << endl;// 证明这种形式不能存放字符串

 cout << "第一个字符串是: "<< pstr[1] <<endl
 <<"数组中元素多占内存的大小是: "<< sizeof (pstr[1])<<endl;
 cout  << endl<<"Pick a lucky star!  "<<endl
 <<"Enter The number of the lucky star:";

 cin >> dice;


 cout << endl;
 if (dice >= 1 && dice <= 6)
  cout << pstart << pstr[dice - 1];
 else
  cout << "Sorry";
 return 0;

}

程序的运行结果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值