question about char* name[]

umm, for char* name[20], what are all the ways to define them during initialization?

I'm trying to char* name[20] = "Something";, but ale is saying it's invalid.
It needs to be const char *.

To initialise, use {}. Eg to initialise 2 elements use:

 
const char* name[20] = {"Something", "and else"};


the remaining elements will be set to nullptr.
char* name[20] is actually an array of 20 pointers to chars. Basically, it is an array pointing to 20 different C-style strings.

You probably want something along the lines of

1
2
char name[20];
strcpy(name, "Something";


Better yet, learn and use the C++ std::string class. It will make life SOOOOOOO much easier for you.
@Brainspell. It depends upon what you want. I thought you wanted to initialise an array of char pointers. However if you just want to initialise one c-style null-terminated string then:

1
2
3
char name[20] = "Something";
char name1[] = "else";
const char* name2 = "a constant";


name is a char array of 20 chars initialised from the given string with unused chars set to null
name1 is a char array of 5 chars (4 for else and 1 for null char) initialised from the given string

For both of these the contents can be changed, although if the contents aren't supposed to be changed then they can set be to const.

name2 is a pointer to a c-style null terminated string stored somewhere determined by the compiler. It's contents can't be changed and hence must be defined as const.
Topic archived. No new replies allowed.