I need to get a pointer to the terminating null char of a string.
I am currently using this simple method: MyString + strlen(MyString) , which is probably pretty good out of context.
However, this solution is not convenient for me, since I have to do it after a string copy:
char MyString[32]; char* EndOfString; strcpy(MyString, "Foo"); EndOfString = MyString + strlen(MyString);
So, I repeat the line around the line twice, the first time in strcpy and the second time in strlen .
I would like to avoid this overhead with a special function that returns the number of characters copied:
size_t strcpylen(char *strDestination, const char *strSource) { size_t len = 0; while( *strDestination++ = *strSource++ ) len++; return len; } EndOfString = MyString + strcpylen(MyString, "Foobar");
However, I fear that my implementation may be slower than the CRT function provided by the compiler (which may use some assembly optimization or another trick instead of a simple char -by-char loop). Or maybe I donโt know of any standard built-in function that already does this?
I benchmarked poor people, iterating 0x1FFFFFFF times three algorithms ( strcpy + strlen , my version is strcpylen and version is user434507 ). Result:
1) strcpy + strlen is the winner in just 967 milliseconds;
2) my version takes much longer: 57 seconds!
3) the edited version takes 53 seconds.
Thus, using two CRT functions instead of a custom โoptimizedโ version in my environment is more than 50 times faster!