I wrote a function for string reversal via pointers, The code is running fine, without bugs, but there are some things i want to know.
Here's my code:
char * xstrrev(char *s1, char *s2){
register char *p = s1;
register char *q = s2;
char *r = s2;
do{
*(s2++) = *(p++); //first copy the string, afterwards, replace it
}while(*p);
p--; //to eliminate trailing '\0' while reversing.
do {
*(q++) = *(p--); //replace contents by reverse contents,
}while(*q);
return r;
}
Here, in the third last line, the *q must have a value '\0'
, because, we copied the exact string previously, So, '\0'
must have been copied.
However, when i replace my
*(s2++) = *(p++);
with
p++;
i.e, i only increase p
to the end-of string, and do not copy the string to s2
, the condition
while(*q)
still works. In this condition, *q
is not supposed to have \0
, right? How does this condition work then?
It's same when i replace, while(*q)
with while(*q!='\0')
EDIT:: It's called as:
char a[110]= "hello";
char f[116];
xstrrev(a,f); //reverse a and put to f
puts(f);