Pass the table to work in c

advertisements

can someone please help me figure out what i'm doing wrong here? i'm getting inaccurate results here. I seem to be getting the first value in the array each time and i cant seem to figure out what i'm doing incorrectly

#include <stdio.h>

int getbillsum ( int price[] );

int main( void )
{
    int itemprice [10];
    int total = 0;
    for (int c=0;c <10;c++ ) //Looping to get item prices
    {
        printf ("\nEnter the price of the item: ");
        scanf (" %d", &itemprice[c]);
    }
    total = getbillsum (itemprice);
    printf ("%d", total);
    return 0;
}

int getbillsum (int price []) //function to sum the values in array
{
    int sum = 0;
    for (int i=0; i<sizeof(price); i++)
    {
        sum+=price[i];
    }
    return sum;
}


You can't pass arrays to functions in C (well, not as an array anyway). Arrays decay into pointers, the sizeof which is always the same (4 for 32 bit systems, 8 for 64 bits).
For more information see paragraph 2.3 here.

The easiest, most common and most reliable way of solving your issue is to pass the length of the array as a second argument:

int getbillsum (int *price, size_t len)
{
    int sum = 0;
    for (int i=0; i<len; ++i)
        sum += price[i];
    return sum;
}
//usage
int main ( void )
{
    int price[10];
    for(int i=0;i<10;++i)
        scanf(" %d", &price[i]);
    printf("Sum: %d\n", getbillsum(price, sizeof(price)/sizeof(*price)));
    return 0;
}

You also had a problem in your code: you added the return statement inside of your loop.
Just a quick-tip: The sum of an array of ints is not unlikely to be too much for a single int to hold, so I'd change the return-type of getbillsum to long, too

I've also edited your question, addressing quite a lot of issues considering how short your code was:

int getbillsum ( price );//missing type, changed to
int getbillsum ( int price[] );//better would be int getbillsum ( int *price ); but considering your question, left it as array
scanf ("%d", &itemprice[c]);//unsafe, changed it to
scanf (" %d", &itemprice[c]);//add space
total = getbillsum (itemprice,9);//why the second param?
total = getbillsum (itemprice);//to match function prototype
return sum;//moved OUTSIDE of the loop...