Search code examples
cstring2dstrcmp

compare string strcmp() function with 2d pointer of string?


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() ?


Solution

  • 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.