Error while printing line

I am creating an algorithm that generates numbers (numbers like strings) from 0 to 9999 and looks for its frequency in the array a [50000].

  char key[4];
  int freq;
  for (int i = 0; i < 10000; i++) {
    sprintf(key,"%04i",i); // save 4 digits in key, if i <1000 save leading 0's
    freq = BruteForceStringMatch(key,a,n); //n length of a.
    printf("%s-%i\n",key,freq);
  }
  free(a);

      

but when i run the program i get it.

.
.
.
9845-7
9846
-10
9847-4
9848-5
-139
9850-3
9851-6
9852-5
9853-4
9854-2
9855-7
9856-5
9857-4
9858-5
9859    -9
9860-3

.
.
.
9968-6
9969    -9
9970-5
9971-4
9972-7
9973-6
9974-6
9975-2
9976-7
9977-4
9978-2
9979-7
9980-3
9981-4
9982-3
9983    -9
9984-6
9985-7
998-8
9987    -9
9988-3
9989    -9
9990-4
9991-3
9992-5
9993-2
9994    -9
9995-5
9996-6
9997-7
9998-7

      

There are tabs in the position of the randoms, sometimes the last digit of the key is eliminated and there is 139113 etc., I have no idea where they came from. I am using gcc version 5.4.0 (GCC) and compile with windows 10 and babun terminal.

Additional Information:

BruteForceStringMatch looks for the frequency of the key in a.

int BruteForceStringMatch(char key[4], char* a, int length ){
  int freq=0;
  int k;
  for (int j = 0; j < length -4; j++) { 
    k =0;
    while(k <4 && key[k] == a[j+k])
      k=k+1;
    if(k == 4) 
        freq++;
  }
  return freq;
}

      

I am getting a 5000 character file.

FILE *inputfile;
  char c;
  int largo = 0;
  char *a = (char *)malloc(50000*sizeof(char *));;
  char *b = (char *)malloc(50000*sizeof(char *));;
  inputfile = fopen("archivo_1.tex", "r");
  if (inputfile == NULL) {
      fprintf(stderr, "Failed to open the file.\n");
      exit(1);
  }
  if (inputfile) {
      for ( int i=0; (c = getc(inputfile)) != EOF; i++){
          a[i] = c;
          //putchar(a[i]);
          largo++;
      }
      fclose(inputfile);
  }

      

+3


source to share


1 answer


It seems to me that your problem is that you have defined the "key" in only four characters, when it should be five or four digits plus a trailing zero. So the zero ends at the first byte "freq" ... then when you set "freq" on line 5, that value is treated by printf (on line 6) as part of the "key" line. In particular, you can see this in the output for values ​​9859 and 8859, where the "freq" value is 9, which is the ASCII code for the tab. Also, for value 9846 and "freq" is 10, which is the ASCII value for line feed (ie Newline) and at 9849, where "frequency" is 13, which is a carriage return, so "-13" prints above the first three characters 9849.



0


source







All Articles