:: Re: [DNG] [OT] [Re: Studying C as t…
トップ ページ
このメッセージを削除
このメッセージに返信
著者: Edward Bartolo
日付:  
To: dng
題目: Re: [DNG] [OT] [Re: Studying C as told. (For help)
Hi,

Again, this is NOT a difficulty but for anyone wanting to comment.

And this is for P. 38 Exercise 1-14

Initially, this gave me the dreaded Segmentation Fault (aka Access
Violation). It was naturally something to do with the array. I was
exceeding the permissible index maximum.

My solution:

#include <stdio.h>

int main() {
#define MAX_LENGTH 26 /* English alphabet has 26 letters */


int char_freqs[MAX_LENGTH];

  int i;
  for (i = 0; i < MAX_LENGTH; ++i)
    char_freqs[i] = 0;


  /*  fill in the frequencies array, char_freqs
   *  Lowercase and uppercase of same letter treated as one letter
   */
  char c;
  while ((c = getchar()) != EOF) {
    if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
        /* in ASCII table 'a' > 'A' */
        /* i.e. if lowercase */
        if (c >= 'a')
          ++char_freqs[c - 'a'];
          else ++char_freqs[c - 'A'];
    }
  }


  /* display the histogram */
  int j;
  for (i = 0; i < MAX_LENGTH; ++i) {
    /* select lowercase as heading for each bar */
    printf("%c \t", i + 'a');
    for (j = 1; j <= char_freqs[i]; ++j)
      printf("#");
    printf("\n");
  }


return 0;
}


Why I was receiving access violations:

 if (c >= 'a')
          ++char_freqs[c - 'a'];
          else ++char_freqs[c - 'A'];


Exchanging 'a' with 'A' in the above causes the program to attempt to
write to array indices that fall beyond the highest index. The OS
responds by sending a signal (SIGSEGV) to terminate the program
immediately.

Edward




On 21/06/2016, Edward Bartolo <edbarx@???> wrote:
> Hi,
>
> This is NOT a difficulty. I am posting my code so that anyone wanting
> to comment can do so.
>
> Pg 38, Exercise: 1-13
> Write a program to print a histogram of the lengths of words in its
> input. Horizontal bars selected.
>
> My solution/code:
>
> #include <stdio.h>
>
> int main() {
> #define MAX_LENGTH 10
>
>
> int word_sizes[MAX_LENGTH];
>
>   int i;
>   for (i = 0; i < MAX_LENGTH; ++i)
>     word_sizes[i] = 0;

>
>   /* fill in the frequencies array, word_sizes */
>   char c;
>   int ws = 0;
>   while ((c = getchar()) != EOF) {
>     if (c == ' ' || c == '\n' || c == '\t') {
>         if (ws > 0) {
>           if (ws > MAX_LENGTH) {
>             printf("\nMAX_LENGTH execeeded, exiting.\n");
>             return -1;
>           }
>           ++word_sizes[ws];
>         }
>         ws = 0;
>       }
>     else ++ws;
>   }

>
>   /* display the histogram */
>   int j;
>   for (i = 0; i < MAX_LENGTH; ++i) {
>     printf("%d chars\t", i);
>     for (j = 1; j <= word_sizes[i]; ++j)
>       printf("#");
>     printf("\n");
>   }

>
> return 0;
> }
>
> Edward
>