r/cs50•
Trollcontrol

[SPOILER] Week 2 Hours array syntax question

SpoilerCS50x

Hi.

I solved this practice problem, and it works as intended.

However it leaves me with a syntax question regarding arrays, particularly when used as function arguments. I have highlighted the code in question in bold

Thank you

:

------------------------------------------------------------------------------------------------------------------------------

#include <cs50.h>
#include <ctype.h>
#include <stdio.h>
float calc_hours(int hours[], int weeks, char output);
int main(void)
{
int weeks = get_int("Number of weeks taking CS50: ");
int hours[weeks];
for (int i = 0; i < weeks; i++)
    {
hours[i] = get_int("Week %i HW Hours: ", i);
    }
char output;
do
    {
output = toupper(get_char("Enter T for total hours, A for average hours per week: "));
    }
while (output != 'T' && output != 'A');
printf("%.1f hours\n", calc_hours(hours, weeks, output));
}
// TODO: complete the calc_hours function
float calc_hours(int hours[], int weeks, char output)
{
float totalhours = 0;
float averagehours = 0;
int i = 0;
for (i = 0; i < weeks; i++)
    {
totalhours += hours[i];
    }
if (output == 'T')
    {
return totalhours;
    }
else
    {
return totalhours / (float) weeks;
    }
}

------------------------------------------------

The question I have is why the arguments in function float calc_hours is written as hours as opposed to hours[] ?

Posted Feb 5, 2023, 11:43 PM UTC

13
Grithga•

[] is not used when calling the function (inside of your call to printf because [] is either part of the type, or used to access a specific element of the array. We never include the type when referencing an existing variable, so we shouldn't include it for that reason, and we are not trying to access a specific element of the array so we also shouldn't include it for that reason. So, since we are not declaring a new variable and we are not accessing a specific element, we do not include the [].

In the declaration on the other hand, we do need to declare the type of our parameter, so the [] is included. The argument is of type int[], not int.

3
TrollcontrolOP•

That makes perfect sense Thank you for the brilliant explanation 🙌🌟🥳

1
TrollcontrolOP•

Any other feedback or suggestions regarding my code is much appreciated, as I'm still a noobie.
Thanks so much

1
TheGavPav•

I have a question, I solved this problem on my own except I couldn't figure out what the compiler wanted me to put as a return value at the end of the function. I ended up putting return totalhours / (float) weeks; like you did in order to finish the problem. But, I don't fully understand WHY that's what works. Can you tell me why you used that as the return value?

1