如何使用字符串文字初始化constchar[]
我想做以下事情:
const char errorMsg [64] ( useApple ? "Error Msg Applen" : "Error Msg Been" );
MyMethod ( errorMsg );
对于带有签名的方法:
MyMethod(const char* errorMessageInput );
我有一个使用 const char* 的方法,我想在发送它之前创建一个局部变量。我无法分配动态内存,但我可以使用比需要更大的数组(在这种情况下,我将其设为 64)。我将如何编译此代码?
回答
您可以声明一个指针,而不是数组
const char *errorMsg = useApple ? "Error Msg Applen" : "Error Msg Been";
实际上,如果方法参数的类型为 ,则无需声明常量数组const char *。
你可以写例如
#include <cstring>
//...
char errorMsg [64];
strcpy( errorMsg, useApple ? "Error Msg Applen" : "Error Msg Been" );
然后使用数组作为方法的参数。
- @zDoctor: This doesn't create an array on the stack. The code has `"Error Msg Applen"` and `"Error Msg Been"` as part of the binary, and this creates a _pointer_ on the stack, that points to one of those.