2

is it possible to do this?

void putAverage(float *avg, int *arrData, int size) {
    int i,sum = 0;
    for(i = 0;i < size;i++) {
        sum += *(arrData + i);
    }
    *avg = sum / size;
}

int main() {
    float i;
    putAverage(&i, {1, 2, 3, 4, 5}, 5);
    printf("%f\n",i);
}

because if i run it, it shows error like this

error: expected expression before '{' token
error: too few arguments to function 'putAverage'
note: declared here

if it possible please make a correction, if not please give me the best way to do it.

2
  • 5
    {1, 2, 3, 4, 5} --> (int[]){1, 2, 3, 4, 5}, *avg = sum / size; --> *avg = (float)sum / size; Commented May 22, 2017 at 23:58
  • 1
    It's simpler to use arrData[i] than *(arrData + i) – and there's no performance difference. Commented May 23, 2017 at 3:58

1 Answer 1

2
#include <stdio.h>

void putAverage(float *avg, const int *arrData, int size) {
    int i,sum = 0;
    for(i = 0;i < size;i++) {
        sum += *(arrData + i);
    }
    *avg = (float)sum / size;
}

int main() {
    float i;
    putAverage(&i, (const int[]){1, 2, 3, 4, 5}, 5);
    printf("%f\n",i);
    return 0;
}

Read this answer for more understanding.

(const int[]){ 1, 2 ,3 ,4 ,5 } is same as

int arr[] = {1, 2, 3 ,4 ,5 };
  foo(arr); //Passing the array

const is added to make sure we don't modify the array by mistake.

(float)sum is for typecasting the integer division and store as float

Sign up to request clarification or add additional context in comments.

1 Comment

Good code but you should also explain what changes you made and why

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.