简体   繁体   English

更改const char指针的问题

[英]Problems with changing a const char pointer

I'm having some issues with changing a char pointer and can't figure out where I'm going wrong 我在更改char指针时遇到一些问题,无法弄清楚我要去哪里

Here's my function for changing the description... 这是我更改说明的功能...

void appointment::changeDescription(const char * s)   //  change an existing description
{

if (desc != NULL)
    strcpy(desc, s);

if (s == NULL)
    return;

}

And here's the function that calls the change description function. 这是调用更改描述功能的功能。

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

} }

It compiles and runs but the description remains the same as the default constructor description... 它可以编译并运行,但其描述与默认构造函数描述相同。

If you use std::string to store the description in the appointment class then you can make things much easier for yourself and for the people who end up working on your code. 如果您使用std::string将描述存储在约会类中,则可以使您自己以及最终使用您的代码的人变得更加轻松。 The changeDescription method would then become this: changeDescription方法将变为:

#include <string>

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

And change the calling code to this: 并将调用代码更改为此:

std::string desc;

Then all of the annoying memory management that causes the problems you are facing are fixed pretty much for free (in terms of programming effort that is). 然后,几乎所有免费的(导致编程困难的)错误修复导致您面临问题的烦人的内存管理。 Generally speaking this is considered to be better idiomatic c++ code than using null terminated C-style char arrays. 一般来说,与使用以空终止的C样式char数组相比,这被认为是更好的惯用c ++代码。

Another thing about your code is that you really should check that s is not null before you try to copy it, not afterwards. 关于代码的另一件事是,您真的应该在尝试复制s之前(而不是之后)检查s是否不为null。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM