【问题标题】:How to convert my string into array of chars如何将我的字符串转换为字符数组
【发布时间】:2020-04-15 13:57:14
【问题描述】:

这是一个问题。当我尝试使用 strncpy_s 对其进行转换时,数组末尾有一些来自内存的“垃圾数据”。即使我用“\0”填充缓冲区。怎么转换清楚?

typedef class Ryadok {
private:
    int LengthOf = 0;
    char text[20];
    string* address;
public:
    Ryadok(string strin) {
        this->text[0] = '\0';
        memset(text, '\0', sizeof(text));
        strncpy_s(text, strin.c_str(), sizeof(text) - 1);
        this->address = &strin;
        for (int i = 0; i < sizeof(strin); i++) {
            cout << this->text[i];
        }
    }
    ~Ryadok() {
    }
}*cPtr;
int main()
{
    Ryadok example("sdsdfsdf");
}

【问题讨论】:

  • 一个问题——为什么需要复制到一个字符数组?为什么不将所有内容都保留为std::string?其次,this-&gt;address = &amp;strin;——这不起作用,因为strin 是一个临时变量。为什么typedef class?为什么不简单地class
  • 您的任务将无法运行——您认为该函数返回后会发生什么?临时变量strin 会发生什么?它消失了——那么你存储的地址会指向什么?
  • 看起来更像是Rube Goldberg 解决问题的尝试。
  • sizeof(strin) 并没有按照你的想法去做。
  • 只需将值string strin 存储到string address(注意address 不再是pointer)。然后,通过address,您将可以分别使用address.c_str( )address.data() 访问底层const char*char*

标签: c++ arrays string char strncpy


【解决方案1】:

使用 c_str() 函数将 std::string 转换为 a-string 的想法。然后我们可以简单地调用 strcpy() 函数将 c-string 复制到 char 数组中

std::string s = "Hello World!";
char cstr[s.size() + 1];
strcpy(cstr, s.c_str());    // or pass &s[0]
std::cout << cstr << '\n';
return 0;

【讨论】:

  • char cstr[s.size() + 1]; -- 不幸的是,这不是有效的 C++。
  • 使用头文件#include &lt;cstring&gt;。它肯定会工作
  • 不,它不起作用。您正在声明一个带有运行时值的数组来表示大小。它不是有效的 C++。您是默认的 g++clang 编译器模式的另一个受害者,在这种模式下,您被愚弄以为 C++ 中存在可变长度数组。
【解决方案2】:

当使用strncpy_s 函数时,您告诉它复制尽可能多的字符以适合您的缓冲区"text"。由于您创建 "example" 实例所用的字符串较短,因此复制功能将在实际字符串结束后继续运行。

这就是你的垃圾的来源。更糟糕的是,您以这种方式冒着分段错误的风险。您的代码可能会访问不允许读取的 RAM 部分。这将导致它崩溃。

尽管复制c_str() 的返回所指向的数据是正确的。 c_str() 返回的指针指向属于 std::string 对象的数据,并且可能被该对象更改甚至无效。 (Read more here)

这是您的代码的修改版本,应该避免垃圾:

typedef class Ryadok {
    private:
        int LengthOf = 0;
        char text[20];
        string* address;
    public:
        Ryadok(string strin) {
            this->text[0] = '\0';
            memset(text, '\0', sizeof(text));

            if(strin.length()+1 <= sizeof(text)) {
                strncpy_s(text, strin.c_str(), strin.length()+1);
            } else {
                //some error handling needed since our buffer is too small
            }

            this->address = &strin;
            for (int i = 0; i < sizeof(strin); i++) {
                cout << this->text[i];
            }
        }
    ~Ryadok() {
    }
}*cPtr;

int main()
{
    Ryadok example("sdsdfsdf");
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-13
    • 1970-01-01
    • 1970-01-01
    • 2013-04-06
    • 2017-12-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-18
    相关资源
    最近更新 更多