How does this array work with this indexing? K & R teachings

I read K & R, currently in chapter 1. After reading the section and trying to solve the problems, I would like to check other solutions on the Internet, just see different methods of solving the same problem.

Exercise 1-14 says that we need to print a histogram of the frequencies of different characters at the input. This solution I found takes into account only the letters of the alphabet:

#include <stdio.h>

#define MAX 122
#define MIN 97
#define DIFF 32

int main(){
  int c = EOF;
  int i, j;
  int array[MAX - MIN];
  printf("%d  ", MAX - MIN);

  for (i = MIN; i <= MAX; i++){
    array[i] = 0;
    printf("%d  ", i);
  }

  while ((c = getchar()) != EOF){
    if (c >= MIN)
    ++array[c];
    else {
      ++array[c + DIFF];
    }
  }

  for (i = MIN; i <= MAX; i++){
    printf("|%c%c|", i - DIFF, i);
    for (j = 1; j <= array[i]; j++){
      putchar('*');
    }
    putchar('\n');
  }

  return 0;
}

, , array[]. 25 (MAX - MIN). 0 24. 97 122. , ?

for (i = 0, i < MAX - MIN; i++)

,

array[97] ... array[122]

EDIT:

printf("%d ", MAX - MIN); printf("%d ", i); , , 97 .

+4
3
int array[MAX - MIN];

25, 197-97 = 25.

 for (i = MIN; i <= MAX; i++){
    array[i] = 0;

array[i] , 25, <<26 > - 97.

, ++array[c]; j <= array[i]; undefined, .

GCC:

source_file.c: In function ‘main’:
source_file.c:14:10: warning: array subscript is above array bounds [-Warray-bounds]
     array[i] = 0;
          ^
source_file.c:20:12: warning: array subscript is above array bounds [-Warray-bounds]
     ++array[c];
            ^
source_file.c:20:12: warning: array subscript is above array bounds [-Warray-bounds]
source_file.c:28:27: warning: array subscript is above array bounds [-Warray-bounds]
     for (j = 1; j <= array[i]; j++){
                           ^

C11 J.2 undefined

  • , * , (6.5.6).

  • , , -, ( lvalue a[1][7] int a[4][5]) (6.5.6).

+2

for , Undefined Behavior, , .

MAX - MIN 25 [97, 122], .

, ++array[c] for (j = 1; j <= array[i]; j++) Undefined, .

PS: MAX - MIN + 1, 26 .

+2

no boundary checking in C, .

,

int array[ MAX - MIN ] ;

sizeof( int ) * (MAX - MIN), , , .

, , c, , , , .

, , .

, -

" "

0
source

Source: https://habr.com/ru/post/1688656/


All Articles