编译器提示要使用更安全的strcpy_s()函数,函数使用方法如下
格式:strcpy_s(pn, strlen(temp) + 1, temp);
temp:要复制的原字符串
strlen(temp) + 1:字符串长度。切记加一,存放结束符‘\0’
pn:要将temp复制到的位置
以下为C++ primer plus 例程中需要改动的(第四章)
// delete.cpp -- using the delete operator
#include <iostream>
#include <cstring> // or string.h
using namespace std;
char * getname(void); // function prototype
int main()
{
//char * name; // create pointer but no storag
//name = getname(); // assign address of string to name
char * name = getname();
cout << name << " at " << (int *)name << "\n";
delete[] name; // memory freed
name = getname(); // reuse freed memory
cout << name << " at " << (int *)name << "\n";
delete[] name; // memory freed again
// cin.get();
// cin.get();
return 0;
}
char * getname() // return pointer to new string
{
char temp[80]; // temporary storage
cout << "Enter last name: ";
cin >> temp;
char * pn = new char[strlen(temp) + 1];
//strcpy(pn, temp); // copy string into smaller space
strcpy_s(pn, strlen(temp) + 1, temp);
return pn; // temp lost when function ends
}