Search code examples
arrayscscanf

How to input for arrays I don't know the length of?


I'm trying to make a program that accepts the number of students enrolled to an exam, and how many points each of them got. I try to loop the inputs but it gives seemingly random numbers in output

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

int main ()
{
    int studenti;
    scanf("%d", &studenti);
    printf("%d ", studenti);
    int niza[studenti];
    for (int i = 1; i <= studenti; i++){
        scanf("%d", &niza[i]);
        i++;
        printf("%d ",niza[i]);
    }
}

What am I doing wrong? Is there another way to add array elements without knowing how big the array will be beforehand because I don't know how big they are when I pass the checks on my uni website.


Solution

  • The primary issue is that the for loop begins with 1 and continues to i <= studenti. In C, arrays begin with index '0' and the final index in this example is studenti - 1.
    Another issue is the for loop increments i and there is an i++; in the body of the loop. i is incremented twice.
    Check the return from scanf. It returns the number of items successfully scanned. Here that would be 1, 0 or EOF.

    #include <stdio.h>
    #include <stdlib.h>
    
    int main ()
    {
        int studenti = 0; // initialize
        if ( 1 == scanf("%d", &studenti)) { // successful scan
            printf("%d ", studenti);
            int niza[studenti]; // variable length array
            for (int i = 0; i < studenti; i++) { // start from index 0
                if ( 1 == scanf("%d", &niza[i])) {
                    printf("%d ",niza[i]);
                }
                else { // scanf returned 0 or EOF
                    fprintf ( stderr, "problem scanning array element\n");
                    return 2;
                }
            }
        }
        else { // scanf returned 0 or EOF
            fprintf ( stderr, "problem scanning\n");
            return 1;
        }
        printf("\n");
        return 0;
    }