-3

I been struggling with this piece of code and I can't really figure out what is wrong with it. The code simply takes an input integer k from the user, passes it to the powerOfTen function along with a pointer of type double, and calculates the result. But, when I store the result inside the *my_dbl and try printing that value through *my_double, I get nothing as a result.

#include <stdio.h>

void powerOfTen(int k, double *my_dbl);

int main()
{
    int k;
    double *my_double;

    scanf("%d", &k);
    power_of_ten(k, my_double);
    printf("%.15lf\n", *my_double);
}

void power_of_ten(int k, double *my_dbl)
{
    double result = 1.0;

    if(k >= 0){
        for(int i = 0; i < k; i++) result = result*10.0;
    } else{
        for(int i = 0; i < (0-k); i++) result = result/10.0;
    }
    // printf("%f\n", result);
    *my_dbl = result;
}

1 Answers1

1

The pointer was never initialized. Easiest fix is:

int main(int argc, char **argv)
{
    int k;
    double my_double;

    k = argc > 1 ? strtol(argv[1], NULL, 10) : 5;
    power_of_ten(k, &my_double);
    printf("%.15lf\n", my_double);
}

In the original code, the uninitialized pointer my_double does not yet point to a valid memory location, so the attempt to write to *my_dbl in the function fails. It basically writes data to some random place in memory. A different fix would be something like: double value; double *my_double = &value. Another might be double my_double[1]. Whatever you do, the address you referenced needs to be a place to which writes are valid.

S.S. Anne
  • 15,171
  • 8
  • 38
  • 76
William Pursell
  • 204,365
  • 48
  • 270
  • 300
  • 1
    @S.SAnne Reading what should be parameters from stdin is bad practice, as is the beginner's use of scanf. The value returned by strtol is being checked...it is assigned to k. – William Pursell Feb 01 '20 at 18:19