Reputation: 155
I am working on a question from Cracking the Coding Interview. The question is: Write code to reverse a C-Style String. And here is the answer I got that is written in c++, but I don't understand the meaning behind increment a char pointer.
void swap(char &a, char &b){
a = a^b;
b = a^b;
a = a^b;
}
void reverse1(char *s){
if(!s) return;
char *p = s, *q = s;
while(*q) ++q;
--q;
while(p < q)
swap(*p++, *q--);
}
The part that I don't understand is in the second function from the first while loop. What is the condition *p
? And why increment q
will chop off the starting character in the string?
For example, if
char s[] = "1234567890";
After you pass s
into function reverse1
, why will ++q
give you a result like "234567890"
?
Upvotes: 0
Views: 2019
Reputation: 96
p
and q
are pointer to char
and both are initialized as the address of the first char
in the string s[]
(as the name of an array in C
is a pointer to its first element). while (*q) q++;
increases q
(the position of char
) until it reaches the end of the string ( NULL
character '\0'
). and --q
decreases the position to point to one before NULL
char which is the last element (char) of the string.
That is why after passing an string to reverse1()
and doing ++q
, the result would start from the second char rather than the first one.
Upvotes: 1
Reputation: 387
Thats the question for '\0'
which terminates the string.
and the result is:
0987654321
as expected from a function called reverse (in Visual Studio 2013
)
Upvotes: -1
Reputation: 997
Strings are arrays. q is pointing to the first character of the string. So when you increase q. q will point to the next character.
Upvotes: 2
Reputation: 2547
C style strings are null(0x00 or /0) terminated.
char s[] = "1234567890";
will be stored in memory like this:
0x31 0x32 0x33 0x34 0x35 0x36 0x37 0x38 0x39 0x30 0x00
The first while loop is searching for end of string.
At start of while loop q
points to 0x31
.
In each iteration q is incremented to point to next memory location.
When q
points to 0x00
loop breaks.
Upvotes: 0