如何使一个不是空终止的C字符串? [英] how to make a not null-terminated c string?
问题描述
我想知道:字符* CS = .....;会发生什么的strlen()和printf(%S,CS)如果CS点内存块是巨大的,但没有'\\ 0'在里面?
我写这几行:
字符S2 [3] = {'A','A','A'};
的printf(str是%S,长度为%D,S2,strlen的(S2));
我得到的结果是:AAA,3,但我认为这样的结果是因为一个'\\ 0'(或0字节)恰好位于该位置S2 + 3。
如何使一个不是空终止的C字符串? strlen的和其他C字符串函数在很大程度上依赖于'\\ 0'字节,如果没有'\\ 0',我只是想知道这条规则更深,更好。
PS:我的好奇心是通过研究所以follw后引起。
如何转换一个const char *到std :: string的
而这些字在该职位:
这实际上是麻烦比它的外观,因为除非该字符串实际上是NUL结尾你不能调用strlen的。
如果这不是空终止,那么它是不是C字符串,而不能使用的功能,如的strlen
- 他们会扬长而去数组的末尾,从而导致未定义的行为。你需要保持长的赛道一些其他的方式。
您仍然可以打印非终止字符数组与的printf
,只要你给的长度:
的printf(str是%.3s,S2);
的printf(str是%* S,s2_length,S2);
或者,如果你有机会到阵列本身,而不是一个指针:
的printf(str是%* S。(INT)(sizeof的S2),S2);
您也已经标记的问题C ++:在语言中,你通常要避免这一切容易出错说大话,并使用的std ::字符串
而不是。 p>
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 '\0' 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 '\0'(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 '\0' byte,what if there is no '\0',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."
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.
这篇关于如何使一个不是空终止的C字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!