问题
Can someone help me understand what line2:char * end = str
and line4:if (str)
do?
void reverse(char *str) {
char * end = str;
char tmp;
if (str) {
while (*end) {
++end;
}
--end;
while (str < end) {
tmp = *str;
*str++ = *end;
*end-- = tmp;
}
}
}
回答1:
The if (str)
test protects you from dereferencing a null pointer and crashing.
The definition char *end = str;
defines the variable end
, a character pointer, and initializes it with the value stored in str
(which is the address of the first character of the string that str
points to).
The rest of the code determines the length of the string, and then arranges to swap pairs of characters from the two ends, working towards the middle of the string. Technically, the original code is not safe if it is passed an empty string (a pointer that points to the null byte at the end of a string). That's because it will decrement end
to one byte before the byte that str
points at. However, there is no guarantee that the address one byte before the start of a string is valid. The string might point to the first byte of a page of memory, and the prior page has never been mapped, leading to crashes or other problems.
It would be better to use strlen()
to determine the length of the string.
void reverse(char *str)
{
if (str != 0 && *str != '\0') // Non-null pointer; non-empty string
{
char *end = str + strlen(str) - 1;
while (str < end)
{
char tmp = *str;
*str++ = *end;
*end-- = tmp;
}
}
}
来源:https://stackoverflow.com/questions/19853014/reversing-a-string-in-place-in-c-pointers