0

i am doing code practicing which is below

int main() {


    int N, Q, cnt;
    scanf("%d", &N);
    char **str1=(char**)malloc(sizeof(char*)*N);
    for(int i=0; i<N; i++) {
        str1[i]=(char*)malloc(sizeof(char)*20);
        scanf("%[^\n]s", str1[i]);
    }
    scanf("%d", &Q);
    char **str2=(char**)malloc(sizeof(char*)*Q);
    for(int i=0; i<Q; i++) {
        str2[i]=(char*)malloc(sizeof(char)*20);
        scanf("%[^\n]s", str2[i]);
    }

    for(int i=0; i<Q; i++) {
        for(int j=0, cnt=0; j<N; j++) {
            // if statement 
            if( strcmp(str2[i], str1[j]) == 0) cnt++;
        }
        printf("%d\n", cnt);
    }


    for(int i=0; i<N; i++){    
       free(str1[i]);
    }
    for(int i=0; i<Q; i++) {
       free(str2[i]);
    }
    free(str1); 
    free(str2);
    return 0;
}

STD input are

4
aaa
bbb
ccc
aaa
3
aaa
bbb
cca

than print out

2
1
0

because

  • 'aaa' is 2 times
  • 'bbb' is 1 times
  • 'cca' is 0 times

 if( strcmp(str2[i], str1[j]) == 0) cnt++;

however the if statement, doesn't count cnt++

whats wrong, my code with strcmp() ?

Barmar
  • 741,623
  • 53
  • 500
  • 612
alexparkjw
  • 113
  • 1
  • 6
  • [don't cast malloc](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc) – Barmar Dec 08 '16 at 09:09

1 Answers1

2

You have two variables called cnt.

One declared on this line:

int N, Q, cnt;

and scoped to the entire function.

One declared on this line:

for(int j=0, cnt=0; j<N; j++) {

and scoped to the for loop.

The statement cnt++ modifies the second one since it's inside the for loop.

The statement printf("%d\n", cnt); prints the first one since it's outside the for loop.

user253751
  • 57,427
  • 7
  • 48
  • 90
  • There are not two variable, cnt. i am 100% sure. can you check again? – alexparkjw Dec 08 '16 at 09:15
  • @alexparkjw There are two variable, cnt. I am 150% sure, can you check again? – user253751 Dec 08 '16 at 09:23
  • Because i check, and i changed the if code like if( strcmp(str2[i], str1[j]) == 0) printf("123\n"); but never print out 123 – alexparkjw Dec 08 '16 at 09:31
  • `int j=0, cnt=0` declares two variables, `j` and `cnt` and initialises them. It does not delare and initialise `j` and then set the existing variable `cnt` to zero. This is called variable shadowing and compilers can warn you about it if you instruct them to do so. – M Oehm Dec 08 '16 at 09:33
  • @doesn't matter cnt is two or tree. ~ for(int i=0; i – alexparkjw Dec 08 '16 at 09:37
  • @alexparkjw Then maybe you have two problems, and *one* of the problems is that you have two different variables called `cnt`. – user253751 Dec 08 '16 at 20:40