Need help with understanding the pointer code.

Write your question here.
char stringCharacter[] = "ABCDEFGH";
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
void reverse(char* stringCharacter)
{
	char *front;
	char *rear;
	char temp;
	
	front = stringCharacter;
	rear = stringCharacter + strlen(stringCharacter) - 1;
	
	while (front < rear)
	{
		temp = *front;
		cout << temp << endl;
		*front = *rear;
		cout << *front << endl;
		*rear = temp;
		cout << *rear << endl;
		
		front++;
		rear--;
	}



The part I'm not quite understanding the code: front = stringCharacter, and rear = stringCharacter + strlen(stringCharacter) - 1; Thus, I want to make sure that my understand is right or not.

When run these code, the *front will point to address 0 which contains 'A', the *rear also point to address 0. However, since the code *rear = .......... contains strlen(stringCharacter) - 1; which is 0 + 7. Now, *rear point to address 7 that contains 'H'.

The loop keep the code repeating as many as necessary.

Am I right?

Can you tell me why do they need to write char* stringCharacter in reverse function argument?
Last edited on
The front and rear store addresses. The *front and *rear access the values at those locations.

The rear does not store "0" at any point. It is set initially to stringCharacter + 7.
(In a = b + c; the b +c is evaluated first and the result of evaluation (an unnamed temporary value) is then assigned to a.)


Names are difficult. On one hand you want to use as descriptive names as possible. On the other seeing seemingly same name in different scopes is confusing.

The reverse() operates on some array. It is not very useful, if it always reverses the same global array. You want to use it with different arrays and therefore you do pass the array (C-string, actually) as argument.

It seems that the caller (or global scope) has array with name "stringCharacter". That name has nothing to do with the name "stringCharacter" in the scope of function reverse().

You could use a different name to make the distinction more clear:
1
2
3
void reverse( char * text ) {
  char * front = text;
  char * rear  = text + strlen(text) - 1;
Topic archived. No new replies allowed.