0

I'm trying to initialize an array of strings in C. I want to set one of the elements of the array from a variable, but I'm getting a compiler error. What's wrong with this?

char * const APP_NAME = "test_app";

char * const array_of_strings[4] = {
    APP_NAME,
    "-f", "/path/to/file.txt",
    NULL
};

The error is error: initializer element is not constant.

1
  • maybe try 'const * const, so 'const * const APP_NAME' Commented Jan 31, 2014 at 23:09

2 Answers 2

3

The standard distinguishes const-qualified variables and compile time constants.

Evaluating a variable (APP_NAME) is not considered to be a compile time constant in the sense of the C standard. This

char const app_name[] = "test_app";

char const*const array_of_strings[4] = {
    &app_name[0],
    "-f", "/path/to/file.txt",
    0,
};

would be allowed, since this is not evaluating app_name but only taking its address.

Also, you always should treat string literals as if they had type char const[]. Modifying them has undefined behavior, so you should protect yourself from doing so.

Sign up to request clarification or add additional context in comments.

1 Comment

Hmm. I tried this but I get warning: initialization from incompatible pointer type. Any idea?
0

I was able to get it to compile with this syntax using gcc 4.6.3:

char* const APP_NAME = "test_app";
char* const array_of_strings[4] = {
    APP_NAME,
    "-f", "/path/to/file.txt",
    NULL
};

You could also try casting to a const (at your own risk) if the compiler rejects everything else:

char* const APP_NAME = "test_app";
char* const array_of_strings[4] = {
    (char* const)APP_NAME,
    "-f", "/path/to/file.txt",
    NULL
};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.