-2

new here :)

double average(int arr[]) {
    int total = 0;
    int i;
    int count = 0;
    double avg;
    int len = sizeof arr / sizeof arr[0];
    printf("%i\n", len);
    for (i=0; i<len; i++)
    {
        total += arr[i];
        count += 1;
    }
    avg = (double) total / count ;
    return avg; }


int main() {
    int array1[5] = {150, 20, 20, 40, 190};

    printf("%f", average(array1));

The function average(int arr[]) aims to find the average of all elements in the array, which is then called in the main function below

Just wanted to ask why the sizeof array1 / sizeof array1[0] is not returning the correct length of my given array (which in this case = 5). It instead returns 2.

Hope you can help! Thanks in advance! :)

Wei Lun
  • 9
  • 1
  • 4
  • `arr[]` parameter it's a reference of `int`, the size it's 8. Because youre getting the pointer to first address. When you access like `arr[1]`you're doing `*arr + sizeof(int)`. First element size it's 4, so .. 2 – Kevin Kouketsu Dec 07 '18 at 16:14
  • BTW: `sizeof` is an operator, *not* a function – joop Dec 07 '18 at 16:15

3 Answers3

1

The problem is that you've passed your array as a parameter to a function. When you pass an array, it is "decayed" by the compiler to a pointer to the first element. This means that there is no way to tell, from within the function, how many elements are in the array.

The expression that you're using to calculate the array size is, then, dividing the size of a pointer by the size of an integer. The result is two because, on many modern platforms, integers are 32 bit and pointers are 64 bit.

Tim Randall
  • 4,040
  • 1
  • 17
  • 39
0

By the time you get inside the average function, arr has already decayed to a pointer, so you can't use sizeof to get the length of the array. Instead, you should pass in the size as a second argument to the function.

As to why you get a resulting size of 2, you probably have:

sizeof int* => 8
sizeof int  => 4
0x5453
  • 12,753
  • 1
  • 32
  • 61
0

When you use int arr[] in your function parameter, you are passing the array as a pointer. Pointers have a size of 8 bytes (because they just hold the address of your memory block). So what you are actually doing is taking sizeof(int*) / sizeof(int), which equals 8 / 4 == 2. What you will need to do is pass the length of your array:

double average(int *arr, int len) {
    int total = 0;
    int i;
    int count = 0;
    double avg;

    printf("%i\n", len);
    for (i=0; i<len; i++)
    {
        total += arr[i];
        count += 1;
    }
    avg = (double) total / count ;
    return avg; }


int main() {
    int array1[5] = {150, 20, 20, 40, 190};

    printf("%f", average(array1, 5));
Kevin K.
  • 1,327
  • 2
  • 13
  • 18