我在修改字符指针方面遇到了一些问题,无法弄清楚我出错的地方
这是我更改说明的功能......
void appointment::changeDescription(const char * s) // change an existing description
{
if (desc != NULL)
strcpy(desc, s);
if (s == NULL)
return;
}
这里是调用更改描述功能的函数。
bool keyBoardEnterAppointment( schedule & sched) // return true if successful
// return false if full
{
if (sched.isFull() == true)
{
cout << "Schedule is FULL." << endl;
return false;
}
else
{
appointment s;
int day, month, year;
char *desc = new char;
long source;
cout << "*/Enter Appointment\\* ";
cout << "Description: "; cin >> desc;
cout << "Source: "; cin >> source;
cout << "Month: "; cin >> month;
cout << "Day: "; cin >> day;
cout << "Year: "; cin >> year;
s.changeDescription(desc);
s.setSource(source);
s.setDay(day);
s.setMonth(month);
s.setYear(year);
sched.addtoSchedule(s);
sched.print(cout);
return true;
}
}
它编译并运行但描述仍然与默认构造函数描述相同...
答案 0 :(得分:2)
如果您使用std::string
将说明存储在约会课程中,那么您可以为自己和最终处理代码的人员提供便利。 changeDescription
方法将成为这个:
#include <string>
void appointment::changeDescription(std::string const& s){
this->desc = s;
}
将调用代码更改为:
std::string desc;
然后,导致您遇到的问题的所有恼人的内存管理都是免费修复的(就编程工作而言)。一般来说,这被认为是比使用空终止的C风格char数组更好的惯用c ++代码。
您的代码的另一个问题是,在尝试复制之前,您确实应该检查s
是否为空,而不是之后。