SM411
SM411

Reputation: 37

Function is returning wrong type C

I have a problem with my function waveres. It is supposed to return a amplitude as a float, but does not. It return a random high number. I think it is the definition in my header file that is not "seen" by the main function. The other functions does work so I did not include them. When the waveres function runs, it prints correct values of amp.

Header file

#include <stdio.h>
#include <math.h>
#include <time.h> /* til random funksjonen */
#include <stdlib.h>

void faseforskyvning(float epsi[]);
float waveres(float S[],float w[],float *x, float *t, float epsi[]);
void lespar(float S[], float w[]);

Main program

#include "sim.h"
main() 
{
  float epsi[9], t = 1.0, x = 1.0;
  float S[9], w[9];
  float amp; 
  faseforskyvning(epsi);
  lespar(S,w);
  amp=waveres(S,w,&x,&t,epsi);

  printf("%f\n", amp);

}

waveres:

#include "sim.h"

float waveres(float S[],float w[],float *x, float *t, float epsi[])
{
  float amp = 0, k;
  int i;

  for(i=0;i<10;i++)
    {
      k = pow(w[i],2)/9.81;
      amp = amp + sqrt(2*S[i]*0.2)*cos(w[i]*(*t)+k*(*x)+epsi[i]); 
      printf("%f\n",amp);
    }
  return(amp);
}

Sample output where the two last number are supposed to be the same.

0.000000
0.261871
3.750682
3.784552
3.741382
3.532950
3.759173
3.734213
3.418669
3.237864
1078933760.000000

A source to the error might be me compiling wrong. Here is a output from compiler:

make
gcc    -c -o test.o test.c
gcc    -c -o faseforskyvning.o faseforskyvning.c
gcc    -c -o waveres.o waveres.c
gcc    -c -o lespar.o lespar.c
gcc test.o faseforskyvning.o waveres.o lespar.o -o test -lm -E
gcc: warning: test.o: linker input file unused because linking not done
gcc: warning: faseforskyvning.o: linker input file unused because linking not done
gcc: warning: waveres.o: linker input file unused because linking not done
gcc: warning: lespar.o: linker input file unused because linking not done

Upvotes: 1

Views: 407

Answers (1)

Dabo
Dabo

Reputation: 2373

You have undefined behavior, you iterate untill 10

for(i=0;i<10;i++)

But your arrays has size 9 which means the biggest index is 8

float epsi[9], t = 1.0, x = 1.0;
float S[9], w[9];

You need to change your loop to

 for(i=0;i<9;i++)

Also your arrays are not initialized, this is also provokes undefined behavior. For example

 float w[9]={0};

initializes all elements of array w with 0

Upvotes: 5

Related Questions