0

This is confusing me a little and I want to fully understand it before moving through the rest of the lecture. I usually code alongside David's examples on screen and was trying to understand why this makes sense

#include <cs50.h>
#include <stdio.h>

int main(void)
{
    int n = get_int("Number of scores: ");
    int scores[n];
    for(int i = 0; i < n; i++)
    {
        scores[i] = get_int("Score %i: ", i + 1);
    }

    printf("Average: TO DO\n");
}

and yet this doesn't (and also produces a run-time error in sandbox):

#include <cs50.h>
#include <stdio.h>

int main(void)
{
    int n = get_int("Number of scores: ");
    int scores[n];
    for(int i = 0; i < n; i++)
    {
        scores[n] = get_int("Score %i: ", i + 1);
    }

    printf("Average: TO DO\n");
}

The error I got was

runtime error: index 3 out of bounds for type 'int [n]'

I'm confused as to why the one in the loop can't be n? I can't even begin to describe my logic on this...

1

When the int array scores is declared here int scores[n]; it will have n elements, indexed to 0. When 3 is entered, the elements of scores are scores[0], scores[1] and scores[2]. There is no scores[3]. (Notice the loop executes until i < n to ensure it will be within bounds). This line scores[n] = get_int("Score %i: ", i + 1); will try to populate scores[3], which produces the "out of bounds" error.

4
  • ah so it'd be like creating a variable that represents a number, then modifying it accidentally by using get_int within a loop? kinda? except with arrays? Okay follow-up question (sorry), why was n stored in an array and not just kept as n, its only purpose is to provide the limit for the number of loops to be executed, am I correct? – laurens_noone Dec 16 '20 at 9:10
  • sorry omitted the @ in the reply – laurens_noone Dec 17 '20 at 15:42
  • "why was n stored in an array": n is not in an array; its only purpose is to define the length of the array (int scores[n];). The loop needs to be limited to the array size so as not to provoke an "out of bounds error". – DinoCoderSaurus Dec 17 '20 at 18:54
  • thank you, I understand now. So it's like declaring the array and then the loop is storing stuff in [0], [1], [2], etc by using i when it increments? I had no idea that was possible, to use a changing variable to designate the address(?) that you want to assign a value to, it's hard to stop thinking of arrays as ordinary variables lol. I will try to shake the comparison, but thank you very much for the explanation – laurens_noone Dec 19 '20 at 1:46

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .