2016-02-19 65 views
-3

我想了解指针工作,我被堵在这条线理解指针/ C++

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

我不明白什么p它等同于。 任何人都可以帮助我吗?

这里是完整的代码。

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; 

} 
+2

使用调试器并找出。 – user657267

+6

没有语言的C/C++。 – Olaf

+1

p不等于,它被分配 –

回答

0

的声明: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 

所以在开始的时候p = s + strlen(s)分配一次,并转化为p = <starting point of the pointer of the s string> + <length of s string>

然后s提高自己的地位和p降低自己的。

for循环位置内,他们只是使用c像临时变量交换字符。

实施例的单词hello

1) hello 
2) oellh 
3) olleh 
+0

我很困惑,用s + strlens(s)。什么是s?一个地址? 。而函数strlen(s)-1是char的个数? – seito

+0

我更新了我的答案。这是可以理解的? – CodeArtist

+0

是的!非常感谢你! – seito

0

在该示例中为循环至s倒退为理念是扭转s中保持的数据。 P被分配了s的最后一个存储单元,尽管指针运算(代码中的p_)正在反向通过s。要访问每个存储单元中的数据,通过将*放在每个变量(* p)的前面来取消指针s和p的引用。

这是否使它更清晰?