[SPOILER] Week 2 Hours array syntax question
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
[]is not used when calling the function (inside of your call toprintfbecause[]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 typeint[], notint.That makes perfect sense Thank you for the brilliant explanation 🙌🌟🥳