Search code examples
carraysalgorithmfor-loopvariable-length-array

Array[0] is changing while entering the "for" loop, can't figure out why


I'm doing a challenge on HackerRank got the method figured out but there's a slight error I cannot figure out. Further information if needed is https://www.hackerrank.com/challenges/sparse-arrays

Basically I only have a problem with arr[0]. It's storing arr[0] as 'aba', then once it hits the first for loop it changes to 'ab'. Why?

Input:

4
aba
baba
aba
xzxb
3
aba
xzxb
ab

Code:

int main() {
  int i, j;
  int n;
  int q;
  scanf("%d", &n);
  char* arr[n];
  char* test[q];
  char* s;
  int counter[q];

  for (i = 0; i < q; i++) {
    counter[i] = 0;
  }

  for (i = 0; i < n; i++) {
    arr[i] = malloc(20);
    scanf("%s", arr[i]);
  }

  scanf("%d", &q);

  for (i = 0; i < q; i++) {
    test[i] = malloc(20);
    scanf("%s", test[i]);
  }

  for (i = 0; i < n; i++) {

    for (j = 0; j < q; j++) {

      if (strcmp(arr[i], test[j]) == 0) {

        counter[j]++;
      } else {
      }
    }
  }
  for (i = 0; i < q; i++) {
    printf("%d\n", counter[i]);
  }
  return 0;
}

Solution

  • You declared test and counter as array of size q before having initialize q. Move there declaration just after scanf("%d",&q);. Also move the initializing loop of counter :

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    int main() {
      int i, j;
      int n;
      int q;
      scanf("%d", &n);
      char* arr[n];
      char* s;
    
      for(i=0; i<n; i++) {
        arr[i]= malloc(20);
        scanf("%s",arr[i]);
      }
    
      scanf("%d", &q);
      int counter[q];
      char* test[q]; 
    
      for(i=0; i<q; i++) {
        counter[i] = 0;
      }
      for(i=0; i<q; i++) {
        test[i]= malloc(20);
        scanf("%s",test[i]);
      }
    
      for(i=0; i<n; i++) {
        for(j=0; j<q; j++) {
          if (strcmp(arr[i],test[j]) == 0) {
            counter[j]++;
          }
        }
      }
      for(i=0; i<q; i++) {
        printf("%d\n", counter[i]);
      }
      return 0;
    }