首页 > 解决方案 > 为什么我尝试以这种方式将字符串转换为 C 字符串失败?

问题描述

我在 VS2019 中的代码不起作用。在最后一行代码编译器抛出一个错误。

#include <iostream>
#include <string>
using namespace std;

struct struct1
{
    string name;
};

void main()
{
    struct1* obj1 = new struct1();
    obj1->name = "Hello";

    // compiler says 'initializing': cannot convert from 'const _Elem *' to 'char [25]'
    char str[25] = (obj1->name).c_str();

}

标签: c++stringc-strings

解决方案


c_str()返回指向字符串字符数据开头的指针。您需要使用类似strncpy().


推荐阅读