[英]How to initialize a const char [] with a string literal
I would like to do the following:我想做以下事情:
const char errorMsg [64] ( useApple ? "Error Msg Apple\n" : "Error Msg Bee\n" );
MyMethod ( errorMsg );
For a method with signature:对于带有签名的方法:
MyMethod(const char* errorMessageInput );
I have a method which takes a const char* and I would like to create a local variable before I send it in. I cannot allocate dynamic memory but I can use a larger array than necessary (in this case I made it 64).我有一个采用 const char* 的方法,我想在发送它之前创建一个局部变量。我无法分配动态 memory 但我可以使用比需要更大的数组(在这种情况下我将其设为 64)。 How would I get this code to compile?
我将如何编译此代码?
Instead of an array you could declare a pointer like您可以声明一个指针,而不是一个数组
const char *errorMsg = useApple ? "Error Msg Apple\n" : "Error Msg Bee\n";
In fact there is no need to declare a constant array if the method parameter has the type const char *
.实际上,如果方法参数的类型为
const char *
,则无需声明常量数组。
You may write for example你可以写例如
#include <cstring>
//...
char errorMsg [64];
strcpy( errorMsg, useApple ? "Error Msg Apple\n" : "Error Msg Bee\n" );
and then use the array as an argument of the method.然后使用数组作为方法的参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.