简体   繁体   English

如何使用字符串文字初始化 const char []

[英]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.

相关问题 为什么我可以将字符串文字初始化为const char *和QString而不是QString *? - Why can I initialize string literal as const char* and QString but not QString*? 如何优雅地初始化矢量 <char *> 用字符串文字? - How to elegantly initialize vector<char *> with string literal? 将空字符串文字初始化或分配给 C 中指向 char 的指针或 C++ 中指向 const char 的指针的原因是什么? - What is the reason to initialize or assign an empty string literal to a pointer to char in C, or a pointer to const char in C++? 如何初始化std :: array <char, N> 用字符串文字省略尾随&#39;\\ 0&#39; - How to initialize a std::array<char, N> with a string literal omitting the trailing '\0' 如何从字符串文字初始化无符号字符数组? - How to initialize an unsigned char array from a string literal? 如何初始化const char **数组 - how to initialize const char** array const char *和literal string之间有什么区别? - What is the difference between const char * and literal string? 字符串文字vs const char *函数重载 - String literal vs const char* function overload 是否可以合法地重载字符串文字和const char *? - Is it possible to legally overload a string literal and const char*? 确定 const char* 是字符串文字还是变量 - Decide if const char* is a string literal or a variable
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM