0

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)

4
  • Change char grades to char* grades. And after scanf, do this. grades = malloc(numGrades); Commented Mar 7, 2013 at 6:33
  • 1
    grades is supposed to be an array (or a pointer to char), not a single char Commented Mar 7, 2013 at 6:33
  • Grades is defined as single character Commented Mar 7, 2013 at 6:34
  • @icepack.. Is there a problem with my suggestion? Commented Mar 7, 2013 at 6:36

2 Answers 2

3

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));
    
Sign up to request clarification or add additional context in comments.

4 Comments

I would just note that VLA's created from user input are a horrible idea (if not just a horrible idea in general...). Use malloc. Also, sizeof(char) is defined to always be 1.
VLAs created on unchecked user input sizes are a bad idea. If you've checked the size for sanity (strictly positive — not zero, not negative — and not too large for some nebulous definition of 'too large', perhaps 4 KiB or 64 KiB), then there's not likely to be any harm done.
About the sizeof(char) thing, just future-proofing in case the OP wants to use some other type. :)
@JoachimPileborg, then use sizeof *grades.
2

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.

Comments

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.