[Pointer and address] Please show me how ....

Hey guys. This is a code that can revese a string by word. But i can't know how it take each individual word.As you see, we have 2 pointer head and tail. Tail point to the lastest individual word in char arry and another to find the head of each word. But why it can print out the whole word instead a char in this case ? Would somebody explant it to me? Thanks alot

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include "stdafx.h"
#include <iostream>
#include <cstring>
using namespace std;
int main(int argc, char **argv)
{
    char input[255];
    char *head; // head of a word.
    char *tail; // tail of a word.
	cout<<"Plz enter a string =.="<<endl;
    cin.getline(input, 255,'\n'); 
	tail = input + strlen(input)-1; 
        tail[1]=0;//Why tail[1] must be 0?
	head=tail;
	cout<<head;
	while (tail >= input) {
        if (tail == 0 || *tail == ' ') {
            tail--; 
        } else {
            tail[1]=0;
			head = tail;	
			cout<<head;
            while (head >= input) {
                if (head == input || *(head - 1) == ' ') {
                    cout << head<<' ' ; // why it can print whole word?
                    tail = head - 1; 
                    break;
                }
                head--; 
				
            }
        }
    }
    cout << endl;
   return 0;
} 
Last edited on
Why tail[1] must be 0?
0 is required to detect the end of the string

why it can print whole word?
head points to the beginning of the word and 0 marks the end.

line 20 replaces the first space after a word with the required 0
Thanks for your help but i'm not clearly know it all. In example, i've modified my code in to this one
1
2
3
4
5
6
7
8
9
10
11
12
13
int main(int argc, char **argv)
{
    char input[255];
    char *head; 
    char *tail;
	cout<<"Plz enter a string =.="<<endl;
        cin.getline(input, 255,'\n'); // read a whole line.
	tail = input + strlen(input)-1; // if you can use <cstring>?
	head=tail-4;
	cout<<head;
        cout << endl;
   return 0;
} 

and run debug and enter this string:"Final Fantasy" and the output it's "ntasy". In code, tail point to "y" so head=tail-4 ---> head point to "n" so i think that this line : cout<<head =n. But why the output it's "ntasy". It makes me so confuse .
Last edited on
well, head is a pointer to char. The stream/cout interprets a pointer to char as a string hence everything is printed until 0 is reached.

If you want to see the 'n' only you need to cout<<head[0]; or cout<<*head; // Note *
As soon as it becomes a pointer the whole string is printed:
cout<<&head[1];
will print "tasy"
yeah i got it. Thanks alot coder777
Topic archived. No new replies allowed.