谭浩强书中指针的错误

来源:互联网 发布:mac 无线键盘连接 编辑:程序博客网 时间:2024/05/16 19:29

p236

 

#include <iostream>
using namespace std;

void copy_string(char *from,char *to){
 for(;*from != '/0';from++,to++)
  *to=*from;
 *to='/0';
}

 

void main(){
 
 char *a="I am a teacher.";
 char *b="You are students.";
 cout<<a<<" "<<b<<endl;
 copy_string(a,b);
 cout<<a<<" "<<b<<endl;
}

 

出现运行错误,理由:

a,b是指向字符串常量的指针,他们相当于:

const char *a="I am a teacher.";

const char *b="You are students.";

不能被修改,可以将他们用数组来实现

char a[]="I am a teacher.";
char b[]="You are students.";

这样就没问题了!

原创粉丝点击