开发者

char arrays length in C

开发者 https://www.devze.com 2023-03-15 22:38 出处:网络
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:

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开发者_JS百科 myString[] = "Hello, World!";

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


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.


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


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.


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


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

int x[] = {1,2,3};


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
*/
0

精彩评论

暂无评论...
验证码 换一张
取 消