Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to return float array from a function?

The output shows the values of k as 0.000 but it should contain actual values that are returned from funcTest().

#include <stdio.h>
#include <stdlib.h>

float *funcTest(int *a, int size)
{
    float p[size];
    int i;
    for(i=0; i< size; i++){
        p[i] = *a;
        p[i]=p[i]/2;
        a++;
    }
    for(i =0; i<size; i++){
        printf("%f\n",p[i]);
    }
    return (float *)p;
}

int main()
{
    int a[4] = {1,5,3,7};
    int size = 4;
    int i,j;
    float *k;
    k = funcTest(&a[0],size);
    for(i =0; i<size; i++){
        printf("%f\n",*k);
        k++;
    }
    return 0;
}

OUTPUT :

0.5
2.5
1.5
3.5
1.5
0.000
0.000
0.000
like image 892
Souvik Kundu Avatar asked Jun 08 '26 01:06

Souvik Kundu


2 Answers

You return a local variable. so, at end of function, local variables are cleaned and do not exist any more. You should use malloc

float *funcTest(int *a, int size)
{
    float *p = malloc(sizeof(float) * size);

And don't forget to free memory when you don't use it anymore with free. If you forget, you will have a memory leak

like image 92
Garf365 Avatar answered Jun 10 '26 08:06

Garf365


In your code, float p[size]; is local to the function funcTest(), so you cannot return the address of it from the function and expect it to be valid in the caller. Once the funcTest() function ends, p will cease to exist. Then, any attempt to make use of the return value will cause undefined behavior, because of invalid memory access.

Instead, you can make p a pointer, allocate memory dynamically using malloc() or family and then, return that pointer to the caller. Dynamically allocated memory will have a lifetime equal to the entire execution of the program (unless deallocated manually), so, even after returning from the function, in the caller, the returned pointer will be valid.

like image 41
Sourav Ghosh Avatar answered Jun 10 '26 10:06

Sourav Ghosh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!