0

I'm struggling on arrays and pointers, my function give an absurd number. I cant manage to find the answer.

float computeAverage(float Array[],int Dim){
    int i;    
    float media, soma;
    for(i = 0;i<Dim;i++)
        soma = soma + Array[i];
    media = soma/Dim;
    return (media);
}
user3386109
  • 34,287
  • 7
  • 49
  • 68
n00bSailor
  • 21
  • 1
  • First, what constitutes absurd? An output would be helpful in identifying what could be going wrong. Also, are you sure Dim is the correct array size? – BTables Aug 30 '19 at 17:53
  • While you are working on the topic, go read [C11 Standard - 6.3.2.1 Other Operands - Lvalues, arrays, and function designators(p3)](http://port70.net/~nsz/c/c11/n1570.html#6.3.2.1p3) – David C. Rankin Aug 30 '19 at 17:58
  • In general, try to always provide your input and output along with an [MCVE](https://stackoverflow.com/help/minimal-reproducible-example). You'll be able to get more accurate and quick answers with complete information that allows us to reproduce and diagnose your error. – skrrgwasme Aug 30 '19 at 17:58

1 Answers1

4
 // you initialize your soma variable (soma = 0)
 float MA (float Array[], int Dim)
 {
     int i;    
     float media, soma = 0;

     for (i = 0; i < Dim; i++)
         soma = soma + Array[i];
     media = soma / Dim;

     return media;
}
lost_in_the_source
  • 10,998
  • 9
  • 46
  • 75
phoenixstudio
  • 1,776
  • 1
  • 14
  • 19
  • Change Dim variable to `Dim = sizeof(Array) / sizeof (Array[0]);` – EsmaeelE Aug 30 '19 at 19:48
  • If you run the program with wrong `Dim` variable return `media` contain garbage values. C not check index of array. – EsmaeelE Aug 30 '19 at 19:49
  • By performing this, passing Dim variable to function is useless – EsmaeelE Aug 30 '19 at 19:51
  • 1
    @EsmaeelIE your suggestions is wrong, that won’t give the size of the array. As it is now, that dim is passed is correct. The variable ’Array’ is a pointer and not an array, so sizeof doesn’t give what you think. – Fredrik Aug 30 '19 at 22:06