字符串常量是存储在常量存储区(文字常量区),因此不能改变其值。
#include <iostream>
using namespace std;int main(void)
{
char *p="C++";
*(p+1)='d';
cout<<*p<<endl;
char ch[]="c++";
ch[0]='d';
cout<<ch<<endl;
return 0;
}
上述程序运行错误,指针p指向常量存储区,对其进行改变是非法的。p更准确的定义是const char *p=“C++”;
ch数组的存储空间被分配在栈中,因此可以对其进行改变。
使用strcat等会对字符串进行改变时的函数时要注意,参数中的char*,是否原本是const char*。如果原本是const char*,则会出现运行时错误。
#include <iostream>
#include <cstring>
using namespace std;
int main(void)
{
char *p="andf";
strcat(p,"sf");
cout<<p<<endl;
return 0;
}
上述程序编译通过,但是运行时出错。
#include <iostream>
#include <cstring>
using namespace std;
int main(void)
{
char *p;
strcat(p,"sf");
cout<<p<<endl;
p[0]='0';
cout<<p<<endl;
return 0;
}
上述程序可以正确运行,而且p所指向的字符串可以改变,证明p不是指向常量存储区。
使用strn版本的前提是,正确计算size。
#include <iostream>
#include <cstring>
using namespace std;
int main(void)
{
char *p1="abcd",*p2="ad";
char p4[1];
strncpy(p4,p2,1);
cout<<p4<<endl;
return 0;
}
对于strncpy:No null-character is implicitly appended to the end of destination, so destination will only be null-terminated if the length of the C string in source is less than num.我们需要在cpy操作之后,显式的添加空字符。
#include <iostream>
#include <cstring>
using namespace std;
int main(void)
{
char *p1="abcd",*p2="ad";
char p3[5];
strncpy(p3,p2,2);
cout<<p3<<endl;
return 0;
}
上述程序得到如下结果:
从结果可以看出我们需要在strncpy操作后加入p3[2]='\0';对应结果如下:
char[]数组在输入时,cin>>ch;和输入string相同,从第一个非空白字符开始,到下一个空白字符结束。
string类型可以通过c_str成员函数返回C风格字符串,它返回的指针指向const char类型的数组。c_str返回的数组并不保证一定有效,对string的 操作会改变返回的值。
#include <iostream>
#include <string>
using namespace std;
int main(void)
{
string str("ajkdfj");
const char *ch=str.c_str();
cout<<ch<<endl;
str="abcd";
cout<<ch<<endl;
return 0;
}
上述程序中,对str的改变同时也改变了ch指向的对象的值。