如何将 const char\* 存储到 char\*?

新手上路,请多包涵

我有 这个按预期工作的代码

 #define MAX_PARAM_NAME_LEN 32

const char* GetName()
{
    return "Test text";
}

int main()
{
    char name[MAX_PARAM_NAME_LEN];
    strcpy(name, GetName());

    cout << "result: " << name << endl;
}

如果我想将结果存储到 char * (因为我使用的框架中的某些功能仅使用 char * 作为输入)而不使用 strcpy (为了代码的实用性和可读性,以及学习),我该怎么办?保持 const ,这很好用:

 const char* name;
name = GetName();

但我仍然有 const

试图只使用 char*

 char* name;
name = GetName();

我得到 invalid conversion from 'const char*' to 'char*' 。这种转换的最佳习惯是什么?

原文由 markzzz 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 453
2 个回答

return "Test text"; 返回一个指向 只读 字符串 字面 量的指针。

如果您使用的函数将 char* 作为输入,并且您有 const char* (例如只读字符串文字),那么您应该提供一个深将从 const char* 开始的字符串复制到此类函数。

否则,如果函数尝试修改只读字符串,您将面临运行时未定义行为的风险。

你目前拥有的就足够了;假设您不能使用 std::string 。 (如果您 可以 使用 std::string 并且 您的所有框架函数都采用 const char* 输入,那么我建议您重构代码以使用 std::string ,并且将该字符串类上的 c_str() 方法的输出传递给您的框架函数。)

最后,如果您的某些框架功能需要 char* 那么您总是可以自己构建一个小型适配器类:

 class Adapter
{
public:
    Adapter(const& Adapter) = delete; /*don't try to copy me please*/
    Adapter& operator=(const Adapter& ) = delete; /*don't try to copy me please*/
    Adapter(const char* s) : m_s(::strdup(s))
    {
    }
    ~Adapter() /*free memory on destruction*/
    {
        ::free(m_s); /*use free to release strdup memory*/
    }
    operator char*() /*implicit cast to char* */
    {
        return m_s;
    }
private:
    char* m_s;
};

Then for a function void foo(char* c) , you can call foo(Adapter("Hello"/*or any const char* */)); and foo can do as it pleases with the char* that’s embedded in the anonymous temporary !您甚至可以增强此类以将构造函数带到 char* 在这种情况下,仅获取指针的浅表副本(并且析构函数不会删除内存)。

原文由 Bathsheba 发布,翻译遵循 CC BY-SA 3.0 许可协议

这种转换的最佳习惯是在整个代码中使用 std::string 。由于您使用的框架将 const char* 作为其输入,因此您始终可以将 c_str() 调用您的 std::string 的结果传递给它:

 std::string GetName() {
    return "Test text";
}

int main() {
    std::string name = GetName();
    int res = external_framework_function(name.c_str());
    cout << "result: " << res << " for " << name << endl;
}

另一个最好的方法是在您的代码中使用 const char*

 const char* name = GetName();

由于您使用的框架需要 const char* 您在这里也很好。

如果您需要一个非常量指针,则无法复制字符串。您可以创建一个为您执行此操作的函数,但您仍需负责释放从中获得的副本:

 char* copy(const char* orig) {
    char *res = new char[strlen(orig)+1];
    strcpy(res, orig);
    return res;
}
...
char *name = copy(GetName());
...
delete[] name;

原文由 Sergey Kalinichenko 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题