而(* + P);而什么(* P){对++}之差{;}虽然(* P ++){;}? [英] what difference between while(*p){p++;} ,while (*++p){;} and while(*p++){;}?

查看:150
本文介绍了而(* + P);而什么(* P){对++}之差{;}虽然(* P ++){;}?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是关于 strcat的功能。

while (*p)
    p++;

while (*++p)
    ;

这两个作品,但

while (*p++)
    ;

不起作用。我认为,第一和第三应该是一样的,但它不是。

does not work. I think first and third should be same, but it's not.

推荐答案

两个

while (*p) p++;

while (*++p) ;

将提前 P 来指向0终结的字符串,而

will advance p to point to the 0 terminator in a string, whereas

while (*p++) ;

将提前 P 指向过去的0终止一个字符。

will advance p to point one character past the 0 terminator.

要明白为什么,让我们假设在内存中的下列字符:

To see why, let's assume the following characters in memory:

Address         0x00 0x01 0x02 0x03
-------         ---- ---- ---- ----
0x8000           'a'  'b'  'c'   0
0x8004           ...

假设 P 从地址0x8000开始。这是第一个循环如何发挥出来:

Assume that p starts at address 0x8000. Here's how the first loop plays out:

1.  *p = 'a'
2.  p = 0x8001
3.  *p = 'b'
4.  p = 0x8002
5.  *p = 'c'
6.  p = 0x8003
7.  *p = 0
8.  end loop

下面是第二个循环如何发挥出来:

Here's how the second loop plays out:

1.  p = 0x8001
2.  *p = 'b'
3.  p = 0x8002
4.  *p = 'c'
5.  p = 0x8003
6.  *p = 0
7.  end loop

和这里的最后一个:

1.  *p = 'a'
2.  p = 0x8001
3.  *p = 'b'
4.  p = 0x8002
5.  *p = 'c'
6.  p = 0x8003
7.  *p = 0;
8.  p = 0x8004
9.  end loop

在过去的版本中,评估 * P ++ 推进即使的值* P 0的指针。

In the last version, evaluating *p++ advances the pointer even if the value of *p is 0.

这篇关于而(* + P);而什么(* P){对++}之差{;}虽然(* P ++){;}?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆