5

In C, you have to declare the length of an array:

int myArray[100];

But when you're dealing with chars and strings, the length can be left blank:

char myString[] = "Hello, World!";

Does the compiler generate the length for you by looking at the string?

Espresso
  • 4,722
  • 1
  • 24
  • 33
  • 2
    You don't have to explicitly declare the length of an `int` array either: `int a[] = {1,2,3};` – mhyfritz Jun 27 '11 at 18:15
  • All answers are correct, all upvoted. I always feel silly when I can't decide which answer is the best. –  Jun 27 '11 at 18:16

6 Answers6

10

Yes, it's the length including the terminating '\0'.

Karoly Horvath
  • 94,607
  • 11
  • 117
  • 176
10

This is not unique to char. You could do this, for instance:

int myNumbers[] = { 5, 10, 15, 20, 42 };

This is equivalent to writing:

int myNumbers[5] = { 5, 10, 15, 20, 42 };

Initialising a char array from a string literal is a special case.

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
5

Does the compiler generate the length for you by looking at the string?

Yes, that's exactly why it works. The compiler sees the constant value, and can fill in the length so you don't have to do it.

Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
3

Yes, the compiler knows the length of the string and allocates the appropriate space.

The Archetypal Paul
  • 41,321
  • 20
  • 104
  • 134
3

It's the same deal if you did something like...

int x[] = {1,2,3};
MGZero
  • 5,812
  • 5
  • 29
  • 46
2

The size of the string literal (not length as in strlen) is used to size the array being initialized.

You can initialize a char array with a string literal which has embedded null bytes. The resulting array will have size for all the bytes after the first (or second, ...) null.

char array[] = "foo\0bar\0baz\0quux";
/* sizeof array is 17
** array[3] is 0
** printf("%s\n", array + 4); prints bar
** array[11] is 0
** printf("%s\n", array + 12); prints quux
** array[16] == 0
*/
pmg
  • 106,608
  • 13
  • 126
  • 198