Americo
Americo

Reputation: 919

C - Declaring an array with an undefined value

I am trying to determine the size of an array by having the user input the size of the array after being prompted (because I don't know how many grades I'll have per test)...

It doesnt seem to like the line where scanf ("%c",&grades[i]);

Here is the whole function:

#include <stdio.h>

 int main (void)
{
int numGrades;
char grades;
char i;
int x;


printf ("Enter The Amount Of Numbers In Your Array: ");
scanf("%i", &numGrades);/*Stores Amount Of Grades In The Array*/

for (x = 0; x < numGrades; ++x)
  {
  printf ("\nEnter the grade: ");
  scanf ("%c",&grades[i]);
  }

return 0; 
}

How can I pass the array size as a parameter so that I can accept an array of any size? (I will be adding a function that will take all the grades and combine them together by letter)

Upvotes: 0

Views: 2063

Answers (2)

Some programmer dude
Some programmer dude

Reputation: 409136

You have two choices:

  1. If your compiler support C99 variable length arrays you could declare the array after you get the size:

    scanf("%i", &numGrades);
    char grades[numGrades];
    
  2. If not then you have to dynamically allocate the array on the heap:

    scanf("%i", &numGrades);
    char *grades = malloc(numGrades * (sizeof *grades));
    

Upvotes: 3

Carl Norum
Carl Norum

Reputation: 224854

You declared grades as a single char, not an array. Either move the declaration to after you read in numGrades and make it a VLA, like this:

char grades[numGrades];

Or use dynamic allocation:

char *grades = malloc(numGrades);

If you choose the latter, don't forget to free() it.

Upvotes: 2

Related Questions