Вопрос

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" 
};
Это было полезно?

Решение

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.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top