user2787790
user2787790

Reputation: 9

Pointers: why the output is 6?

The output of the program below is 6. I am not able to figure out why. When I trace it out by hand, I am getting 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); 
}

Upvotes: 0

Views: 136

Answers (3)

Nemanja Boric
Nemanja Boric

Reputation: 22157

if(*p1++ == *p2++) is reading both p1 and p2 character by character. When the characters are the same, it will increase count by 5, else it will decrement it by 3. But, there is another thing that you didn't pay attention to: strlen(p1) will always be different in each iteration, because p1 will change. So, in each iteration, you also need to check its value.

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

Upvotes: 9

hyde
hyde

Reputation: 62797

The trick here is, strlen(p1) changes every iteration. So loop condition goes

0 <= 10  +5
1 <= 9   -3
2 <= 8   +5 
3 <= 7   -3
4 <= 6   +5
5 <= 5   -3

So equal characters are a, c, e, shown as +5 above. Total is 6.

Upvotes: 2

Marc
Marc

Reputation: 2639

Your program stops when i>strlen(p1) because you are changing p1 each time you do *p1++.

When it computes the condition strlen returns the size from the las char.

If you store the value in a variable at the beginning (before your loop) it should work.

Anyway, try to avoid pointer arithmetic...

Upvotes: 0

Related Questions