【问题标题】:Why didn't work C++ code(strncpy_s)?为什么不工作 C++ 代码(strncpy_s)?
【发布时间】:2018-02-11 13:07:10
【问题描述】:

我是 C++ 初学者。

当我学习过 C++ 类时,这个示例代码不起作用。

此代码被 NameCard 类构造函数中的 strncpy_s() 函数中断。

我尝试调试,但找不到原因。

你能帮帮我吗? This is full source code

祝你有美好的一天。

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

【问题讨论】:

  • “没有工作”以什么方式?编译时会出错吗?如果是这样,请将错误复制粘贴到问题中。
  • 感谢您的回答,抱歉我的解释不够。此代码的错误发生在运行时,而不是编译时...
  • 什么错误发生在运行时?当您运行程序时会发生什么?您期望会发生什么?
  • 真正的唯一问题是你为什么不使用std::string。从字面上复制需要对 C++ 字符串进行简单的赋值。
  • 感谢@MichaelWalz 解决了。这是我的第一个问题,因为我出生了,但我非常感谢您的回复(JJJ,Arnav Borborah)。下一次,我会写一份更详细的问卷。 :)

标签: c++ strncpy


【解决方案1】:

您误用了new 运算符。

所有行如:

new char(strlen(name) + 1);

应替换为:

new char[strlen(name) + 1];

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

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

但最好首先使用std::string

【讨论】:

  • new char(X)整数值 X 填充缓冲区(适当调整以适应 char)。与 ASCII 或任何其他字符编码没有内在联系。
【解决方案2】:

以下是我将如何为 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;
}

【讨论】:

  • 非常非常感谢 Eljay。 :)
  • @user9345804 • 非常欢迎您!我希望返工作为演示/示例有帮助和教育意义。 :-) C++ 是一种强大的语言,但也有许多锋利的边缘。
  • @Eljay 示例代码看起来像其他语言。 :) 我会努力学习 C++。
  • @user9345804 • Arnav Borborah 链接到大量优秀的 C++ 书籍。
  • @Eljay 我想这只是我很挑剔,但总的来说,我认为你不应该使用 auto 作为 name 变量的类型,因为它们没有那么长,并且使用 auto 可能造成缺乏清晰度。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-11
  • 1970-01-01
  • 2018-11-05
  • 1970-01-01
相关资源
最近更新 更多