-3

I'm trying to understand how pointers work and I'm stuck at this line

for (p = s + strlen(s) - 1; s < p; s++, p--)

I don't understand p what it's equated to. can anyone help me?

here's the full code.

void Reverse(char *s){
    char c, *p;

    for (p = s + strlen(s) - 1; s < p; s++, p--){
        c = *s;
        *s = *p;
        *p = c;
    }
}


int main(){
    char ch[] = "!dlroW olleH";
    Reverse(ch);
    printf("%s", ch);

    return 0;

}
seito
  • 1
  • 2

2 Answers2

0

On the statement: for (p = s + strlen(s) - 1; s < p; s++, p--)

`p` contains the pointer to the end of the `s` string.
`s` contains the pointer to the beginning of the string.
`strlen()` calculates the length of the string

So in the beginning p = s + strlen(s) is assigned only once and translates to p = <starting point of the pointer of the s string> + <length of s string>

Then s increases his position and p decreases his own.

Inside the for loop position they just swapping characters using c like temporary variable.

Example for the word hello:

1) hello
2) oellh
3) olleh
CodeArtist
  • 5,534
  • 8
  • 40
  • 65
0

In this example the for loop is going backwards through s as the idea is to reverse the data held in s. P is being assigned the last memory location of s and though pointer arithmetic (p-- in the code) is going backwards through s. To access the data in each memory location the pointers s and p are dereferenced by putting * in front of each variable (*p).

Does this make it any clearer?

Careful Now
  • 260
  • 1
  • 9