Hi all,
I'm self-learning. I tried to reverse a c-string using pointer. For example href->ferh...Here is my solution:
void reverse(char *ptr)
{
int len;
char *begin, *end, temp;
length = strlen(ptr);
begin = ptr;
end = ptr;
for (int i = 0 ; i < ( length - 1 ) ; i++ )
end++;
for ( int i = 0 ; i < length/2 ; i++ )
{
temp = *end;
*end = *begin;
*begin = temp;
begin++;
end--;
}
}
Though, I have searched online and see a different solution. I don't understand some points, can someone help me to figure it out? (I'm trying to learn the new thing).
void reverse(char *str)
{
int len = strlen(str);
char *ptr = (str + len);
while (ptr-- != str)
cout << *ptr;
}
at the line with char *ptr = (str + len), What is that mean? As I understand,we assign str and it's length to ptr. For example: str is "Too bad" in array will be |T|o|o| |b|a|d|'\0'| but when we assign *ptr = (str + len),it will be |T|o|o| |b|a|d|'\0'|'\0'|'\0'|'\0'|'\0'|'\0'|'\0'|'\0'|'\0'|
is that correct?
The second question is if my understanding is correct (as above) then how the while loop work when ptr-- is go from address of each element but str stand for the address of whole string.
it will be |T|o|o| |b|a|d|'\0'|'\0'|'\0'|'\0'|'\0'|'\0'|'\0'|'\0'|'\0'|
is that correct?
No, you have pointer arithmetic here. ptr will point the end of the string (i.e. the final '\0')
The second question is if my understanding is correct (as above) then how the while loop work when ptr-- is go from address of each element but str stand for the address of whole string.
str points to the beginning of the string. The while loop will decrement the pointer ptr as long as it is not equal to the beginning of the string.
By the way: That while loop has a weak point. If the string is empty (or str is null) it will go infinite.
Better: while (ptr-- > str)
Thank you very much coder777. You're awesome. Can I have 1 more question please?
For example: if *ptr = str that mean *ptr points to the whole address of(|T|o|o| |b|a|d|'\0'|) in another word, it points to the address of whole string or it points to the address of starting letter T? because some c++ lesson I learned from youtube.com look like *ptr points to the address of whole string.
Thank you very much!