Search code examples
cfunctionglobal-variables

Global Function not returning the correct values


I'm trying to compile the first non zero value of a vector, using a global function. But as I compile, it returns the original value k1=k2=1, when it's supposed to be k1=0 and k2=2. No? My code looks like this:

#include<math.h>
#include<stdlib.h>

int primeiro(float vec[], int f)
{
  f=0;

    while(vec[f]==0)
    {
     f++;
    }

 return f;
}


int main()

{
float poli1[4]={1,2,3,4}, poli2[4]={0,0,5,6};
int k1=1, k2=1, i;

printf(" \n");

for(i=0; i<4; i++)
  {
     printf("%g\t", poli1[i]);
  }

printf("\n \n");

for(i=0; i<4; i++)
  {
     printf("%g\t", poli2[i]);
  }

printf("\n \n");

primeiro(poli1, k1);
printf("%d \n", k1);
primeiro(poli2, k2);
printf("%d \n", k2);
                
}```

Solution

  • You never change k1 and k2, so they have their original value.

    Maybe

    primeiro(poli1, k1);
    primeiro(poli2, k2);
    

    was meant to be

    k1 = primeiro(poli1, k1);
    k2 = primeiro(poli2, k2);