指针:为什么输出为6?

0 c string pointers

以下程序的输出是6.我无法弄清楚原因.当我手工追踪它时,我得到了5.

#include<stdio.h>
#include<conio.h>

main()
{
    int i,count=0; 
    char *p1="abcdefghij"; 
    char *p2="alcmenfoip"; 

    for(i=0;i<=strlen(p1);i++) { 
        if(*p1++ == *p2++) 
            count+=5; 
        else 
            count-=3; 
    } 
    printf("count=%d",count); 
}
Run Code Online (Sandbox Code Playgroud)

Nem*_*ric 9

if(*p1++ == *p2++)被同时读取p1p2逐个字符.当字符相同时,它将增加count5,否则它将减少3.但是,还有一件事你没有注意:strlen(p1)每次迭代总是不同的,因为p1会改变.因此,在每次迭代中,您还需要检查其值.

p1   p2 count   i   strlen (before entering into the loop body)
a    a   5      0   10
b    l   2      1   9
c    c   7      2   8
d    m   4      3   7
e    e   9      4   6
f    n   6      5   5  <- No more - this is the last one
Run Code Online (Sandbox Code Playgroud)