Why can't the compiler get the string length for an array of strings?

Note: This question was influenced by this answer .

Valid code is C:

char myString[] = "This is my string"; 

This will highlight a line of length 18 (including the \0 character) on the stack and assign it the specified value.

However, the following:

 char myStrings[][] = {"My 1st string", "My 2nd string", "My 3rd string"}; 

invalid by specifying the error "array type has an incomplete element type".

Therefore, I must specify the array as follows:

 char myStrings[][20] = {"My 1st string", "My 2nd string", "My 3rd string"}; 

Where 20 is a number that is larger than my longest string.

This compiles and works as expected.

If the compiler can dynamically perceive the length of a string when allocating one line on the stack, why can't it do this for an array of strings?

Edit:

Just to clarify, this is not a problem in real life that I am experiencing - it is just a painful curiosity.

+4
source share
4 answers

Itโ€™s one thing to โ€œdetermineโ€ the length of one line. Another thing is to calculate the maximum lengths of many lines. There is a certain intuitive qualitative difference between the two. Thus, the authors of the language probably decided that the former is simple and useful, but the latter is too complex and less useful.

+5
source

Why not do:

 const char* myStrings[] = {"My 1st string", "My 2nd string", "My 3rd string"}; 
+4
source

Because the compiler sees this

 char myStrings[][20] = {"My 1st string", "My 2nd string", "My 3rd string"}; 

a

 char myStrings[][20] = {(char*), (char*), (char*)}; 

Then, errrr ... hmmm, with "compiler magic", he can copy the characters in these (char*) to the array myStrings [0] and myStrings [1], ....


Edit

You cannot have jagged arrays in C. Suppose you have

 char my_strings[][] = {"a", "ab", "abc", "foo foo fo foo foo", "abc", "ab", "a"}; 

my_strings[0] requires the same space as my_strings[3] , because the language requires the elements of the array to be contiguous, and it needs a specific size for each array.

  my_strings in memory
     'a' '\ 0' '\ 0' ... '\ 0' but must be a definite size
     'a' 'b' '\ 0' ... '\ 0' definite size
     ...
     'f' 'o' 'o' ... '\ 0'
     ...

To find the maximum size and initialize the array (s), the compiler needs to do two passes over string literals.

+3
source

char myString [] = "..." is a 1-dimensional array and it will work. char myStrings [] [] = {"...", "..."} is a two-dimensional array with (possibly) different string lengths, and this will not work. char myStrings [] [20] is a 2D array with a fixed string length and it will work.

According to C standards, the compiler cannot determine the length of a string in 2D arrays.

But I think it is possible in Java.

+2
source

All Articles