0

I'm new here so I apologize if I've done anything wrong in asking this question. I'm in C and I'm trying to add one to the value of an element in an array every time the element's number is read from the file. I have it set to terminate when it reads the number 30. I believe I am making out of bounds errors or something along those lines because the values printed out after I try the following code are insane.

int main(){

  int votes[20];
  FILE *input;

  input = fopen("votes.txt", "r");
  int currentVote;   
  while(currentVote != 30){
    fscanf(input, " ");
    fscanf(input, "%d",&currentVote);
    if(currentVote == 30){
      break;
    }
    votes[currentVote] += 1;
  }  
  fclose(input);
  int i;
  int l = 19; 
  int x;
  for(i = 0; i <= l; i++){
    x = i;
    printf("%d is %d\n",i,votes[x]);
  }

  return 0;
}

Unfortunately, this is the output that I get.

0 is 1
1 is 1
2 is 1
3 is 1
4 is 1835627637
5 is 1600061542
6 is 1869833335
7 is 1952802656
8 is 1
9 is 1
10 is 1
11 is 1
12 is 2
13 is 1
14 is 4196110
15 is 1
16 is 1
17 is 1
18 is 1
19 is 1

This is the input text file:

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 30

Thank you in advance.

1 Answer 1

1

Your vote array is not initialized to 0 so some of the values are garbage values hence the unexpected values.

int votes[20] = {0};
Sign up to request clarification or add additional context in comments.

1 Comment

It's a mistake everyone has made at least once.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.