mrVentures
mrVentures

Reputation: 131

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). How would I get this code to compile?

Upvotes: 4

Views: 1127

Answers (1)

Vlad from Moscow
Vlad from Moscow

Reputation: 311068

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 *.

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.

Upvotes: 6

Related Questions