문제

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