编译环境vs2010,c++
#include "stdafx.h"
#include <iostream>
#include <cstring>
using namespace std;
class Words{
public:
Words(char *s)
{
len=strlen(s);
str=new char[len+1];
strcpy_s(str,len,s);
}
void disp();
char operator[](int n);
private:
int len;
char *str;
};
char Words::operator[](int n)
{
if(n<0||n>len-1)
{
cout<<"数组下标超界!\n";
return ' ';
}
else
return *(str+n);
}
void Words::disp()
{
cout<<str<<endl;
}
int main()
{
Words word("This is C++book.");
word.disp();
cout<<"第1个字符:";
cout<<word[0]<<endl;
cout<<"第16个字符:";
cout<<word[15]<<endl;
cout<<"第26个字符:";
cout<<word[25]<<endl;
return 0;
}
str=new char[strlen(s)+1];这句话怎么注释了,如果你不给指针分配内存,那就是个野指针了,根本不知道指针指向什么空间,你直接拷贝肯定有问题
通过调试发现 strcpy_s(str,len,s);这行代码出了问题...很明显你对strcpy_s这个函数的理解不是很深。第二个参数代表的是缓冲区的大小,即缓
冲区的大小应该大于源字符串的长度至少为一,这也正是strcpy_s较strcpy函数的安全之处,你也看到了你的缓冲区大小不够的时候编译器是
制止的...所以正确的修改方法是将len换为len+1,这样缓冲区大小就够了,因为你的len长度没有包含'\0'