How to make string c with zero completion?

I am wondering: char * cs = ..... what will happen to strlen () and printf ("% s", cs) if cs points to a block of memory that is huge, but without \ 0 'in it? I am writing 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 that this result is due to the fact that "\ 0" (or 0 bytes) is in the location s2 + 3. how to make line c with zero termination? strlen and another c string function are highly dependent on the byte '\ 0', and if not '\ 0', I just want to know this rule deeper and better.

ps: my curiosity is caused by studying the following publication on SO. How to convert const char * to std :: string and this word in this post: "It is actually more complicated than it seems, because you cannot call strlen if the string is actually not nul terminated."

+5
source share
7 answers

If this is not terminated by zero, then this is not a C string, and you cannot use functions such as strlen- they will move away from the end of the array, causing undefined behavior. You will need to track the length differently.

You can still print an array of characters endlessly with printf, if you specify the length:

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

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

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

++: malarkey std::string.

+22

A "C" . C . - , C.

, , , C . strlen, strcpy strcat. , , char*, , .

? , , . ( , . , .) , , , . , . ++ std::string, char* ; .

+9

, , strlen , , . , , . strlen , C-, , , , , , .

C std: . , , 3 , std:, 3 , . .

, CRT C, -. API, , API .

, , CRT, (, strncpy), , .

+3

: strlen , . , , 3 , , , 4- .

. C () . C ; API-, ... .:)

:

  • A: char s2[4] = { 'a','a','a', 0 }; // good if string MUST be 3 chars long
  • B: char *s2 = "aaa"; // if you don't need to modify the string after creation
  • C: char s2[]="aaa"; // if you DO need to modify the string afterwards

, B C , - , , B C - , A , .

+3

, char \0 . , str*() char -array. , .

.

, char arr[3] = {'a', 'a', 'a'};, char. \0, ​​C, stdout.

+1

, , .

, .

char s2[] = {'a','a','a','\0'};
0

C 7 - . C11 7.1.1p1 :

  1. - , .

( )

If the string definition is a sequence of characters ending with a null character, a sequence of non-zero characters that do not end with a null character is not a string, period.

0
source

All Articles