0

I have something like:

static const char *array[] = {
    "One String",
    "Second String",
    "Third",
    "etc",
};

I want to define a new string variable new_var and initialize it with the first string in array. So array[0]. So something like:

static const char new_var[] = &array[0];

However the error from the compiler is invalid initializer on this line.

I am trying to initialize the variable outside the scope of any functions and so would prefer not to use any string.h functions like strcpy etc.

Please suggest any tricks which might be used here.

2 Answers2

0

Would be helpful if you posted the actual error, but, your types were wrong, so that's probably the problem. Instead, try:

static const char* new_var = array[0];
MuertoExcobito
  • 9,741
  • 2
  • 37
  • 78
0

You have a type error. &array[0] is a pointer to a char. new_var is an array of chars.

If you want to initialize new_var to a non-literal string then you have to copy the characters and append a terminating 0. But before that you have to define new_var to be of a sufficiently large length.

You may want a different design. Eg having new_var be a pointer to char; then you could use static const char *new_var = &array[0];. Pointers are the way to share an array of values.

philipxy
  • 14,867
  • 6
  • 39
  • 83
  • Thanks for your response. Yes, mis-match of types but unfortunately I now get the error initializer element is not constant with char *new_var = &array[0]; –  May 22 '15 at 02:30
  • [How to create a Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve) – philipxy May 22 '15 at 02:38