Question

Why can the compiler know how much strings there are but not how much chars they contain? For example, this works:

char songs[][30]{ 
  "A string", 
  "Another string" 
}; 

And this one doesn't:

char songs[][]{ 
  "A string", 
  "Another string" 
};
Was it helpful?

Solution

If you're fine with constant strings, then you don't.

const char *strings[] = {
    "foo",
    "bar",
    "baz",
    "quux",
};

The only time when you'd need to give it the length of the strings is if you were trying to make a two dimensional array of chars, like

char strings[][5] = {
    "foo",
    "bar",
    "baz",
    "quux",
};

C can guess the outermost dimension, but the items in the array have to be complete types, and an array of char of unknown length is not complete, but both char[5] and const char * are.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top