HHHH
HHHH

Reputation: 101

C: Problem using pointers to update variable in main from different function

I'm new with pointers and C. When I first print Q I get 0 as expected. Once I've then updated Q to the value of q I print it out again and get -1 as expect. However, when I then print Q out as part of the main function I am getting 0 again. What am I doing wrong with my pointers?

#include <stdio.h>
#include <math.h>

void decompose(double k, int *S, int *Q, double *F);

int main(){
    double k, F;
    int S, Q;
    k = 0.75;
    decompose(k, &S, &Q, &F);
    /*Printed third*/
    printf("%g\n", k);
    printf("%i\n", S);
    printf("%i\n", Q);
    printf("%g\n", F);
    return(0);
}

void decompose(double k, int *S, int *Q, double *F){
    if (k > 0){
        *S = 1;
    }
    else{
        *S = -1;
        k = k * -1;
    }
    
    int b = 2, q = 0;
    if (k > 1){
        while (pow(b, q) < k){
            q = q + 1;
        }
        q = q - 1;
    }
    else if (k < 1){
        while (pow(b, q) > k){
            q = q - 1;
        }
        /*Printed first*/
        printf("%i\n", q);
        printf("%i\n", *Q);
    }
    *Q = q;
    /*Printed second*/
    printf("%i\n", q);
    printf("%i\n", *Q);
    *F = frexp(k, Q);
}

Upvotes: 0

Views: 58

Answers (1)

Eric Postpischil
Eric Postpischil

Reputation: 222640

frexp changes the int pointed to by its second argument. Since you are passing Q for the second argument, it changes *Q.

When you call it, the first argument, k, has the value .75. frexp sets the int pointed to by the second argument to the exponent of two needed to scale the first argument to the interval [½, 1). Since .75 is already between ½ and 1, .75 = .75•20, so *Q is set to zero.

Upvotes: 3

Related Questions