Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
229 views
in Technique[技术] by (71.8m points)

What happens when I initialize a char array without setting the array size in C

When I initialize a char array like char str1[] = {'a','b','c'} (array size is not set) and finding it's length using loop until str1[i] != '', I get length = 4. In contrast, when I initialize like char str2[10] = {'a','b','c'} (array size is set) and finding the length using using same way, I get length = 3. Why str1[3] contains a garbage value but not in str2[3]?

question from:https://stackoverflow.com/questions/65866366/what-happens-when-i-initialize-a-char-array-without-setting-the-array-size-in-c

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

char str1[] = {'a', 'b', 'c'}; creates an array of 3 characters, with the values 'a', 'b', and 'c'. The size of the array is 3, which you can see with sizeof str1 (this returns the number of bytes, but as a char is defined to be 1 byte it's the same as the number of elements). Trying to calculate the length of the string contained in this array causes undefined behavior, since str1 does not contain a C-style string as it has no '' terminator. Your loop calculating this goes out of the bounds of the array.

char str2[10] = {'a', 'b', 'c'}; creates an array of 10 characters, with the values 'a', 'b', 'c', and 7 ''s. The size of the array is 10. Calculating the length of the string in str2 gives you 3, since str2[3] is '';

If you want to create an array containing a C-style string without specifying the size, you can do char str[] = {'a', 'b', 'c', ''};, or more simply, char str[] = "abc";.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...