I need help with array return using pointer. Please see the codes below. Code 1 works fine but Code 2 gives me wrong output.
Code 1 :-
#include <stdio.h>
#include <stdint.h>
float *arrayproduct(float *passedarray);
int main(void)
{
float array[] = {2,4,6,8.5};
float *result;
result = arrayproduct(array);
printf("Elements of modified array are %f\n%f\n%f\n%f\n", result[0],result[1],result[2],result[3]);
return 0;
}
float *arrayproduct(float *passedarray)
{
int i;
float product[4]={};
float *ptr;
ptr = product;
for(i=0;i<4;i++)
{
ptr[i] = passedarray[i] - 1;
}
return ptr;
}
The output of Code 1 is :- Elements of modified array are
1.000000
3.000000
5.000000
7.500000
Code 2 :-
#include <stdio.h>
#include <stdint.h>
float *arrayproduct(float *passedarray);
int main(void)
{
float array[] = {2,4,6,8.5};
float *result;
int i;
result = arrayproduct(array);
for(i=0;i<4;i++)
{
printf("%f\n",result[i]);
}
return 0;
}
float *arrayproduct(float *passedarray)
{
int i;
float product[4]={};
float *ptr;
ptr = product;
for(i=0;i<4;i++)
{
ptr[i] = passedarray[i] - 1;
}
return ptr;
}
The output of Code 2 is :- 1.000000
-40110188476235776.000000
138619665717382032373921611776.000000
0.000000
Can someone please explain the issue here? Where am I making a mistake?
Thanks