Ulfric Storm
Ulfric Storm

Reputation: 129

How to return an floating point array

I need a function that creates an array with some floating points.

double * my_function( )
{
    static double arr[10] = {20, 21, 22, 23, 24, 25, 26, 27, 28, 29};

    return arr;
}


int main ()
{
    double *first_pos;
    int i;

    first_pos = my_function();
    for ( i = 0; i < 10; i++ )
    {
        printf( "%d", *(first_pos + i));
    }

return 0;
}

This prints some "random" numbers.

I'm a confused about pointers/arrays!

Upvotes: 0

Views: 97

Answers (2)

J Eti
J Eti

Reputation: 302

I think it is %lf (long float) for doubles, and %f for normal floats

like this

  first_pos = my_function();
  for ( i = 0; i < 10; i++ ){
    printf( "%lf\n", *(first_pos + i));
  }

the output it gives me is

20.000000
21.000000
22.000000
23.000000
24.000000
25.000000
26.000000
27.000000
28.000000
29.000000

Upvotes: 0

John Kugelman
John Kugelman

Reputation: 361899

Your pointer/array usage is fine.

printf("%f", *(p + i));

Print doubles with the %f specifier. %d is for ints.

Upvotes: 6

Related Questions