Shaka
Shaka

Reputation: 11

How do I get input for an array from a user in C programming?

I am new to C and I've run into a bit of a problem when it comes to user input for an array.

Here is the code

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    int n, i;
    int score [n];
    printf("Number of scores: ");
    scanf("%d", &n);
    for(i=0; i<n; i++){
       printf("score: ");
       scanf("%d", &score[i]);
    }
    return 0;
}

It does not matter what value I set for n. It always prompts the user 4 times.

Upvotes: 1

Views: 10699

Answers (2)

Olupo
Olupo

Reputation: 420

If your using an array with unknown size during compilation, I would suggest using memory allocation. So the user determines the array size while running the program.

#include  <stdio.h>
#include <stdlib.h>

int main(void)
{
    int n, i;
    int *score;
    printf("Number of scores: ");
    scanf("%d", &n);

    score = (int *)malloc(sizeof(int)*n);

    for(i=0; i<n; i++){
       printf("score: ");
       scanf("%d", &score[i]);
    }
    free(score)
    return 0;
}

The malloc function allocates memory with the size of n and returns a pointer to the allocated memory.

Upvotes: 1

Lundin
Lundin

Reputation: 213306

As mentioned in comments, you must change this:

/* bad */
int score [n];
printf("Number of scores: ");
scanf("%d", &n);

into this

/* good */
printf("Number of scores: ");
scanf("%d", &n);
int score [n];

This since C executes code from top to bottom like when you are reading a book. It will not "double back" a few rows above and fill in n once it has been entered by the user. At the point where you declare int score [n], n must already be known.

Upvotes: 1

Related Questions