【问题标题】:How to initialize a const char [] with a string literal如何使用字符串文字初始化 const char []
【发布时间】:2021-04-01 22:27:37
【问题描述】:

我想做以下事情:

const char errorMsg [64] ( useApple ? "Error Msg Apple\n" : "Error Msg Bee\n" );
MyMethod ( errorMsg );

对于带有签名的方法:

MyMethod(const char* errorMessageInput );

我有一个采用 const char* 的方法,我想在发送它之前创建一个局部变量。我无法分配动态内存,但我可以使用比需要更大的数组(在这种情况下,我将其设为 64 )。如何编译这段代码?

【问题讨论】:

  • const char* errorMsg = useApple ? "Error Msg Apple\n" : "Error Msg Bee\n";
  • 或者甚至只是:MyMethod ( useApple ? "Error Msg Apple\n" : "Error Msg Bee\n" );
  • 首选std::string 或std::string_view 而不是char*

标签: c++ arrays constants declaration c-strings


【解决方案1】:

你可以声明一个指针,而不是一个数组

const char *errorMsg = useApple ? "Error Msg Apple\n" : "Error Msg Bee\n";

如果方法参数的类型为const char *,实际上不需要声明一个常量数组。

你可以写例如

#include <cstring>

//...


char errorMsg [64];

strcpy( errorMsg, useApple ? "Error Msg Apple\n" : "Error Msg Bee\n" );

然后使用数组作为方法的参数。

【讨论】:

  • @zDoctor:这不会在堆栈上创建数组。代码将"Error Msg Apple\n" 和"Error Msg Bee\n" 作为二进制文件的一部分,这会在堆栈上创建一个指针,它指向其中一个。
猜你喜欢
  • 2013-12-23
  • 2015-03-22
  • 2010-09-29
  • 2022-11-17
  • 2012-07-27
  • 1970-01-01
  • 1970-01-01
  • 2020-01-03
  • 2012-03-19
相关资源
最近更新 更多