How can I add numbers to a table using scanf

advertisements

I want to add numbers to an array using scanf What did i do wrong? it says expected an expression on the first bracket { in front of i inside the scanf...

void addScores(int a[],int *counter){
    int i=0;
    printf("please enter your score..");
    scanf_s("%i", a[*c] = {i});
}//end add scores


Your code suggests that you expect that your array will be dynamically resized; but that's not what happens in C. You have to create an array of the right size upfront. Assuming that you allocated enough memory in your array for all the scores you might want to collect, the following would work:

#include <stdio.h>

int addScores(int *a, int *count) {
  return scanf("%d", &a[(*count)++]);
}

int main(void) {
  int scores[100];
  int sCount = 0;
  int sumScore = 0;
  printf("enter scores followed by <return>. To finish, type Q\n");
  while(addScores(scores, &sCount)>0 && sCount < 100);
  printf("total number of scores entered: %d\n", --sCount);
  while(sCount >= 0) sumScore += scores[sCount--];
  printf("The total score is %d\n", sumScore);
}

A few things to note:

  1. The function addScores doesn't keep track of the total count: that variable is kept in the main program
  2. A simple mechanism for end-of-input: if a letter is entered, scanf will not find a number and return a value of 0
  3. Simple prompts to tell the user what to do are always an essential part of any program - even a simple five-liner.
  4. There are more compact ways of writing certain expressions in the above - but in my experience, clarity ALWAYS trumps cleverness - and the compiler will typically optimize out any apparent redundancy. Thus - don't be afraid of extra parentheses to make sure you will get what you intended.
  5. If you do need to dynamically increase the size of your array, look at realloc. It can be used in conjunction with malloc to create arrays of variable size. But it won't work if your initial array is declared as in the above code snippet.
  6. Testing for a return value (of addScores, and thus effectively of scanf) >0 rather than !=0 catches the case where someone types ctrl-D ("EOF") to terminate input. Thanks @chux for the suggestion!