为什么C++代码不起作用(strncpy_s)?
Why didn't work C++ code(strncpy_s)?
我是C 初学者。
当我研究C 类时,此示例代码不起作用。
此代码被namecard类构造函数中的strncpy_s((func中断。
我尝试调试,但找不到原因。
你能帮我吗?这是完整的源代码
祝您有美好的一天。
NameCard(char *name, char *phone, char *company, char *position)
{
this->name = new char(strlen(name) + 1);
this->phone = new char(strlen(phone) + 1);
this->company = new char(strlen(company) + 1);
this->position = new char(strlen(position) + 1);
strncpy_s(this->name, strlen(name) + 1, name, strlen(name));
strncpy_s(this->phone, strlen(phone) + 1, phone, strlen(phone));
strncpy_s(this->company, strlen(company) + 1, company, strlen(company));
strncpy_s(this->position, strlen(position) + 1, position, strlen(position));
}
您已滥用new
操作员。
所有行,例如:
new char(strlen(name) + 1);
应替换为:
new char[strlen(name) + 1];
new char(X)
为一个单个字符分配一个缓冲区,该缓冲区将填充其ASCII代码为X
的字符。
new char[X]
为X
chars分配缓冲区;这就是您想要的。
,但最好的是首先使用std::string
。
这是我将如何为C 17的代码重新编写。
#include <cstddef>
#include <iostream>
#include <memory>
#include <string>
using std::cout;
using std::endl;
using std::move;
using std::ostream;
using std::string;
class NameCard;
ostream& operator<<(ostream&, NameCard const&);
class NameCard
{
private:
string _name;
string _phone;
string _company;
string _position;
public:
NameCard(string name, string phone, string company, string position)
: _name{move(name)}
, _phone{move(phone)}
, _company{move(company)}
, _position{move(position)}
{
}
NameCard(NameCard const& c)
: _name{c._name}
, _phone{c._phone}
, _company{c._company}
, _position{c._position}
{
}
~NameCard()
{
}
void print(ostream& o) const
{
o << _name << " " << _phone << " " << _company << " " << _position;
}
};
ostream& operator<<(ostream& o, NameCard const& c)
{
c.print(o);
return o;
}
int main()
{
auto James = NameCard{"James", "11231123", "la", "manager"};
cout << James << endl;
auto James2 = James;
cout << James2 << endl;
return EXIT_SUCCESS;
}
相关文章:
- strncpy之后的char数组的错误行为
- 在 MFC 中使用 strncpy() 复制字符串时截断的数据
- gcc臂中strncpy的替换
- 使用 strncpy 复制 tcp 流会导致故障吗?
- C++/Arduino:strcpy()、strncpy() 和 memcpy() 在无符号字符上不起作用
- C strncpy意外输出
- 比strncpy更好地复制字符阵列的部分方法
- 编译代码时麻烦 - strncpy char*和string
- DLL 调用涉及 strncpy() 的方法
- 如果strncpy将随机数据复制到缓冲区中会发生什么
- 为什么 vsnprintf 没有像 strncpy 那样写入相同数量的字符
- Strncpy只能与固定长度的数组一起使用
- strncpy 无法正确修剪 - 相同的长度
- 使用Strncpy在C++中创建一个简单的文本编辑器
- strncpy向我的char数组添加了额外的字符
- 如何将strncpy()转换为WCHAR
- strncat & strncpy help C++
- strncpy运行时检查失败#2错误c++
- strncpy和strcat的工作方式与我认为的c++不同
- 将 strcpy 替换为 strncpy