【问题标题】:Write to a C++ char array写入 C++ 字符数组
【发布时间】:2018-09-26 19:01:24
【问题描述】:

我有一个导出 char* 的库,我可以在其中生成一条消息,然后调用 send 来发送消息(通过网络)。如何在代码中向导出的缓冲区写入非常简单的消息?

我写了四种不同的方法来写消息,没有一个是理想的:

class Lib {
  char msg[100];

public:
  Lib() {
    // nullify the buffer
    msg[0] = 0;
  }

  char* get_buffer() {
    return msg;
  }

  void send() {
    std::cout << "Message is: " << msg << std::endl;
    // nullify the buffer for the next send
    msg[0] = 0;
  }

};

int main () {
  {
    Lib lib;
    char* buf = lib.get_buffer();

    // Method 1 is tedious
    buf[0] = 'H';
    buf[1] = 'e';
    buf[2] = 'l';
    buf[3] = 'l';
    buf[4] = 'o';
    buf[5] = 0;

    lib.send();
  }

  {
    Lib lib;
    char* buf = lib.get_buffer();

    // Method 2 doesn't work
    buf = "Hello";

    lib.send();
  }

  {
    Lib lib;
    char* buf = lib.get_buffer();

    // Method 3 involves a copy
    string str = "Hello";
    str.copy(buf, str.size());

    lib.send();
  }

  {
    Lib lib;
    char* buf = lib.get_buffer();

    // Method 4 involves a copy
    char* c_arr = "Hello";
    std::memcpy(buf, c_arr, 6);

    lib.send();
  }
}

输出是:

Message is: Hello
Message is: 
Message is: Hello
Message is: Hello

第一种方法对我来说似乎很乏味。第二种方法不起作用,因为buf 然后指向内存中包含“Hello”的新位置。第三种和第四种方法涉及创建临时内存缓冲区和内存副本。

我想要类似于 buf = {'H', 'e', 'l', 'l','o'}; 的东西,但这仅在构建时有效。

更不用说我在方法 2 和方法 4 中都有一个编译警告,g++-7.3

warning: ISO C++ forbids converting a string constant to ‘char*’ [-Wwrite-strings]

【问题讨论】:

  • 您的警告是说您正在将字符串文字转换为char*。这是 c++ 不再支持的东西。他们应该只分配给const char*
  • 最简单的解决方案是让Lib::msg 成为std::string
  • char* send() 你没有从那个方法返回任何东西
  • 抱歉,改成void send()
  • 给你一个缓冲区。您将不得不在某些时候将数据复制到其中以使缓冲区有用。

标签: c++ arrays char


【解决方案1】:

如果您从库中获得char*,并且您无法控制该部分,则需要复制一些数据。当您获得由库指定的内存位置时,这是不可避免的。注意第一种方法也是抄的,只是手动的。
我会在代码末尾使用std::string,然后将内存复制到缓冲区。
所以我想方法 3 可能是最好的一种,但我真的希望库也为您提供缓冲区大小,并且您应该确保不要复制太多。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-19
    • 1970-01-01
    • 2020-09-27
    • 2011-11-07
    • 2017-08-31
    相关资源
    最近更新 更多