Code:#include <stdio.h> #include <string.h> int main(void) { int i; char str1[] = "abcdefghijklm..."; char str2[100]; for (i = 0; str1[i]; i++) str2[i] = str1[i]; str2[i] = '\0'; printf("%s\n", str2); return 0; }
Code:#include <stdio.h> #include <string.h> int main(void) { int i; char str1[] = "abcdefghijklm..."; char str2[100]; for (i = 0; str1[i]; i++) str2[i] = str1[i]; str2[i] = '\0'; printf("%s\n", str2); return 0; }
Because when str[i] hits a null ('\0', 0x00, %00, \000, 0) than it will break the loop, because it is 0. The middle statement is the check statement, like the portion inside a while(), execution occurs while it is non-zero.
Yep, to add some code to Tonto's explanation:
could have been written:Code:for (i = 0; str1[i]; i++)
That is basically what is happening, whether it is written explicitly, or implicitly. I would say the latter example is clearer though.Code:for (i = 0; str1[i] != '\0'; i++)
~/
Last edited by kermit; 08-19-2005 at 04:46 PM.
Though kermit's latter example with the explicit compare to '\0' is clearer, having an implicit test for the '\0' character is a popular idiom in C and should be easily recognisable. The code could also be written as:
Code:#include <stdio.h> #include <string.h> int main(void) { int i = 0; char str1[] = "abcdefghijklm..."; char str2[100]; while (str2[i] = str1[i++]); printf("%s\n", str2); return 0; }