看看这个程序,数组元素去哪了?

sinat_30330131 2015-09-25 11:52:15
#include<iostream>
#include<cstring>
int main()
{
using namespace std;
char animal[20] = "bear";
const char * bird = "wren";//"wren"的地址赋给了bird指针。
char * ps;
cout << animal << " and ";
cout << bird << "\n";
//cout << ps "\n";ps没有指向一个被分配好的内存,输出会有问题。
cout << "Enter a kind of animal: ";
cin >> animal;//cin最好是输入在一个数组中,这样若输入比较短,不超过数组范围,就是安全的。
//但如果输入在bird中,bird指向一个字符串常量,在部分编译器中字符串常量为只读常量,修改则会有危险。
//cin >> ps;这属于严重错误,ps并没有指向一个被分配好了的内存。
ps = animal;//只是复制地址并不复制字符串,这样这两个指针将指向相同的内存单元和字符串。
cout << ps << "!\n";
cout << "Before using strcpy():\n";
cout << animal << " at " << (int *) animal << endl;
cout << ps << " at " << (int *) ps << endl;
ps = new char[strlen(animal) + 1];
strcpy(ps,animal);
cout << "After using strcpy():\n";
cout << animal << " at " << (int *) animal << endl;
cout << ps << " at " << (int *) ps << endl;
delete [] ps;
system("pause");
return 0;

C++ Primer Plus上的一个样例。
后面有cin >> animal,可animal数组前面明明还有一个"bear",但是后面cout << animal的时候只显示cin输入的对象,那么"bear"去哪了?还存储在数组当中吗?
...全文
149 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
lm_whales 2015-09-27
  • 打赏
  • 举报
回复
飞了
新数据,覆盖旧数据,毕竟使用的是同一个数组
赵4老师 2015-09-25
  • 打赏
  • 举报
回复
乍看起来c++的cin、cout、ifstream、ofstream在输入、输出上比c的scanf、printf、fscanf、fprintf、fread、fwrite简单,不用格式控制符! 但是不用格式控制符,输入输出恰好是你期望的格式的时候好说;等到输入输出不是你期望的格式的时候,你就会觉得还是用格式控制符更方便、更靠谱。 摒弃cin、cout、ifstream、ofstream! 使用scanf、printf、fscanf、fprintf、fread、fwrite。
fly_dragon_fly 2015-09-25
  • 打赏
  • 举报
回复
animal是个数组, 你用cin, 它只保存最后一次的值

33,311

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 新手乐园
社区管理员
  • 新手乐园社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧