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
332 views
in Technique[技术] by (71.8m points)

c - Strings without a '' char?

If by mistake,I define a char array with no as its last character, what happens then?

I'm asking this because I noticed that if I try to iterate through the array with while(cnt!=''), where cnt is an int variable used as an index to the array, and simultaneously print the cnt values to monitor what's happening the iteration stops at the last character +2.The extra characters are of course random but I can't get it why it has to stop after 2.Does the compiler automatically inserts a character? Links to relevant documentation would be appreciated.

To make it clear I give an example. Let's say that the array str contains the word doh(with no ''). Printing the cnt variable at every loop would give me this: doh+ or doh^ and so on.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

EDIT (undefined behaviour)

Accessing array elements outside of the array boundaries is undefined behaviour.
Calling string functions with anything other than a C string is undefined behaviour.
Don't do it!

A C string is a sequence of bytes terminated by and including a '' (NUL terminator). All the bytes must belong to the same object.


Anyway, what you see is a coincidence!

But it might happen like this

                        ,------------------ garbage
                        | ,---------------- str[cnt] (when cnt == 4, no bounds-checking)
memory ----> [...|d|o|h|*|0|0|0|4|...]
                  |   |   \_____/  -------- cnt (big-endian, properly 4-byte aligned)
                  \___/  ------------------ str

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

...