dereference operator with pointers

Hi guys I am just reversing a string and I find when I leave out the dereference operator I get strange results it seems to print the following to the console



m
Zm
cZm
FcZm
BFcZm
dBFcZm
AdBFcZm



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
  void reverseString(char *str,int size){

    char* start = &str[0];
    char* end = &str[size];

    char* current = end;

    while(current != start){

        cout << current << endl;
        current--;

        if(current == start){

            cout << current << endl;
            break;
        }
    }
}



but when I use the * operator to derefence the address of current which contains an element of an array it works fine and displays what I expected



mZcFBdA





1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

void reverseString(char *str,int size){

    char* start = &str[0];
    char* end = &str[size-1];

    char* current = end;

    while(current != start){

        cout << *current;
        current--;

        if(current == start){

            cout << *current;
            break;
        }
    }
}


how come in the first example the output is the way it is,I understand how the second one is because I am dererencing the pointer but in the first I am not derefencing the pointer so shouldn't it print the memory address?


thanks
When you pass a char* to cout, it outputs the char at that location and all following locations in memory until it finds the value zero.

When you pass a char to cout, it outputs the char at that location.
thanks repeater =)

is it not the other way around?

when I passed the current pointer to a char to cout without the * operator it printed the char in that location

and when I passed it without the * operator to cout it printed the whole array

*EDIT I think I get it now so the reason it first prints m is because current position is at char m and it prints to the char terminator then current-- decrements current to point to Z so now it prints everything up the char term which is Zm and so on?

and when you pass *current the char to a cout it just prints the char?

thanks
Last edited on
is it not the other way around?


As you have found, no.

To summarise:

Pass a char - output one char.
Pass a char pointer - output every byte from that memory position onwards until the value zero is encountered.
Topic archived. No new replies allowed.