inwik
inwik

Reputation: 13

Declaring size of Array in C

folks!

I have an issue with the declaration of an array in C. I have to write a little program in Java which displays the amount of each letter in a text file as well as the total amount of letters. To educate myself further I also write every homework in C as well. In Java it completely works out, so I guess I have a big misunderstanding of arrays in C.

I declared an int array with the size 26. So I thought the compiler allocates memory for 26 integers. My output is a simple for loop with printf("%d",alphabet[m]); . But I get weird results. Some indexes are correct, some have very large numbers in it and others even have negative numbers. If I change the array size to int alphabet[2500]; it totally works out but I do not have any clue why... It does not make any sense, since with index 26 he should allocate 26 integers. Well apparently it make sense, otherwise it would not work. Has anyone a hint for me, I would appreciate it!

The text has a total amount of 5000 characters (whitespaces not included) with an average amount of ~150-200 per letter if this is important.

My Code:

int len;
int alphabet[26];
int m;
FILE *handler;

if(handler!=NULL)
{
  for(m=0;m<=25;m++)
  {
    char buffer = 0;
    handler=fopen("text.txt","r");
    while((buffer=fgetc(handler)) != EOF)
    {
      if(buffer==(char)65+m)
      {
        alphabet[0+m]++;
      }

      if(isalpha(buffer))
      {
       len++;
      }
    }
    fclose(handler);
  }
}

[... else print(error) and fclose ...]

for(m=0;m<=25;m++)
{
  printf("[%c]  n: %5d \n",65+m,alphabet[m]);
}

Upvotes: 1

Views: 1822

Answers (3)

DWright
DWright

Reputation: 9500

Aside from the answers about initializing the array (this is vital, those are good answers), you'll want to rearrange your logic a bit I think. Instead of looping over each element of alphabet, you can have each new character of input "drive" things. For each character, check if it's a candidate for alphabet and adjust the count accordingly. Right now, by looping over the alphabet in your for loop, you are doing everything 26 times which is not necessary.

So the only loop you need is the while loop.

Upvotes: 0

juanchopanza
juanchopanza

Reputation: 227608

There may be other errors, but one big problem with your code is that the elements of the array are not initialized before you attempt to modify them by applying the post-fix increment operator ++. This is undefined behaviour, which may explain the "weird results". You can zero-initialize all the elements of the array like this:

int alphabet[26] = {0};

Upvotes: 1

Carl Norum
Carl Norum

Reputation: 225252

You did declare the right sized array, but you didn't initialize it. That means it's potentially filled with random data. Make sure to set it all to zero before using the ++ operator:

int alphabet[26] = { 0 };

Upvotes: 3

Related Questions