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

c++ - how to make a not null-terminated c string?

i am wondering :char *cs = .....;what will happen to strlen() and printf("%s",cs) if cs point to memory block which is huge but with no '' in it? i write these lines:

 char s2[3] = {'a','a','a'};
printf("str is %s,length is %d",s2,strlen(s2));

i get the result :"aaa","3",but i think this result is because that a ''(or a 0 byte) happens to reside in the location s2+3. how to make a not null-terminated c string? strlen and other c string function relies heavily on the '' byte,what if there is no '',i just want know this rule deeper and better.

ps: my curiosity is aroused by studying the follw post on SO. How to convert a const char * to std::string and these word in that post : "This is actually trickier than it looks, because you can't call strlen unless the string is actually nul terminated."

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

If it's not null-terminated, then it's not a C string, and you can't use functions like strlen - they will march off the end of the array, causing undefined behaviour. You'll need to keep track of the length some other way.

You can still print a non-terminated character array with printf, as long as you give the length:

printf("str is %.3s",s2);
printf("str is %.*s",s2_length,s2);

or, if you have access to the array itself, not a pointer:

printf("str is %.*s", (int)(sizeof s2), s2);

You've also tagged the question C++: in that language, you usually want to avoid all this error-prone malarkey and use std::string instead.


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

...