为什么不能使用C++代码(strncpy_s)?

-1 c++ strncpy

我是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));
}
Run Code Online (Sandbox Code Playgroud)

Jab*_*cky 5

你误用了new操作员.

所有行如:

new char(strlen(name) + 1);
Run Code Online (Sandbox Code Playgroud)

应该替换为:

new char[strlen(name) + 1];
Run Code Online (Sandbox Code Playgroud)

new char(X)为一个单独的char分配一个缓冲区,该缓冲区将填充ASCII代码所在的字符X.

new char[X]X字符分配缓冲区; 这就是你想要的.

但最好是std::string在第一时间使用.