更改常量字符指针时出现问题

Problems with changing a const char pointer

本文关键字:问题 指针 常量 字符      更新时间:2023-10-16

我在更改字符指针时遇到了一些问题,无法弄清楚哪里出了问题

这是我更改描述的函数...

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;
}

}

它编译并运行,但描述与默认构造函数描述相同......

如果您使用 std::string 将描述存储在约会类中,那么您可以为自己和最终处理您的代码的人让事情变得更容易。然后,changeDescription方法将变为:

#include <string>
void appointment::changeDescription(std::string const& s){
    this->desc = s;
}

并将调用代码更改为:

std::string desc;

然后,导致您面临的问题的所有烦人的内存管理几乎都是免费修复的(就编程工作而言)。一般来说,这被认为是比使用以空结尾的 C 样式 char 数组更好的惯用 c++ 代码。

关于代码的另一件事是,您确实应该在尝试复制之前检查s是否为空,而不是之后。