C++中字符串复制时指针的使用

C++中字符串复制时指针的使用

程序清单 4.20演示了如何使用不同形式的字符串。它使用了两个字符串库中的函数。函数 strlen()我们以前用过,它返回字符串的长度。函数 strcpy()将字符串从一个位置复制到另一个位置。这两个函数的原型都位于头文件 cstring(在不太新的实现中,为stringh)中。该程序还通过注释指出了应尽量避免的错误使用指针的方式,

// ptrstr.cpp -- using pointers to strings
#include <iostream>
#include <cstring>              // declare strlen(), strcpy()
int main()
{
    using namespace std;
    char animal[20] = "bear";   // animal holds bear
    const char * bird = "wren"; // bird holds address of string
    char * ps;                  // uninitialized

    cout << animal << " and ";  // display bear
    cout << bird << "\n";       // display wren
    // cout << ps << "\n";      //may display garbage, may cause a crash

    cout << "Enter a kind of animal: ";
    cin >> animal;              // ok if input < 20 chars
    // cin >> ps; Too horrible a blunder to try; ps doesn't
    //            point to allocated space

    ps = animal;                // set ps to point to string
    cout << ps << "!\n";       // ok, same as using animal
    cout << "Before using strcpy():\n";
    cout << animal << " at " << (int *) animal << endl;
    cout << ps << " at " << (int *) ps << endl;

    ps = new char[strlen(animal) + 1];  // get new storage
    strcpy(ps, animal);         // copy string to new storage
    cout << "After using strcpy():\n";
    cout << animal << " at " << (int *) animal << endl;
    cout << ps << " at " << (int *) ps << endl;
    delete [] ps;
    // cin.get();
    // cin.get();
    return 0; 
}

下面是该程序的运行情况:

bear and wren
Enter a kind of animal:fox
fox!
Before using strcpy():
fox at 0x0065fd30
fox at 0x0065fd30
After using strcpy():
fox at 0x0065fd30
fox at 0x004301c8

程序清单 4.20中的程序创建了一个char 数组(animal)和两个指向char 的指针变量(bird和ps)。该程序首先将 animal数组初始化为字符串“bear”,就像初始化数组一样。然后,程序执行了一些新的操作,将char 指针初始化为指向一个字符串:

const char*bird ="wren";// bird holds address of string

记住,“wren”实际表示的是字符串的地址,因此这条语句将“wren”的地址赋给了 bird 指针。(一般来说,编译器在内存留出一些空间,以存储程序源代码中所有用引号括起的字符串,并将每个被存储的字符串与其地址关联起来。)这意味着可以像使用字符串“wren”那样使用指针 bird,如下面的示例所示:

cout <<"A concerned "<<bird <<" speaks\n";

字符串字面值是常量,这就是为什么代码在声明中使用关键字const的原因。以这种方式使用 const 意味着可以用 bird 来访问字符串,但不能修改它。第7章将详细介绍const指针。最后,指针 ps未被初始化,因此不指向任何字符串(正如您知道的,这通常是个坏主意,这里也不例外)。接下来,程序说明了这样一点,即对于cout 来说,使用数组名 animal 和指针 bird 是一样的。

对C++感兴趣的朋友点这里:C/C++课程

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值