更改常量字符指针时出现问题
Problems with changing a const char pointer
我在更改字符指针时遇到了一些问题,无法弄清楚哪里出了问题
这是我更改描述的函数...
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
是否为空,而不是之后。
相关文章:
- 关于 c++ 函数中指针赋值的简单问题
- 链表指针问题
- C++ 关于指针取消引用的技术问题
- C++中的指针和常量问题不大
- 包含矢量指针的结构的内存释放问题
- 指针问题:从不兼容的类型"int"分配给"int *"
- 将字节数组转换为带有字节序问题的指针
- 关于如何使用指向主窗口的指针的 QT 问题
- 当成员值从指针更改为非指针时,C++常量问题
- 为什么循环会导致指针出现问题?
- 使用指针计算堆栈问题的大 O 表示法
- 构造函数 (C++) 中的 char 指针参数存在问题
- 指向包含对齐 C 结构C++类的 C 指针的对齐问题
- 涉及指针和手动实现的矩阵类的问题
- 从基指针到派生的强制转换问题
- 迭代器的指针操作问题
- 64 位迁移问题:指针更改
- C++模板使用问题指针
- 跳到C++第13章练习问题4-指针
- 用std::pair数组初始化std::map问题(指针错误?)