Question

I'm trying to take the sqrt of a variable int *msg in C.

I am trying to get the squareroot of message

int main(int argc, char **argv) {
    int *msg;
    ...
    while(N!=0) {
        if (g_continue == 0) {
            break;
        }
        if(mq_timedreceive(qdes, (char *)&msg, sizeof(int), 0, &ts) == -1){
            printf("Error Message Missing");
        }
        if(sqrt((float *)msg)*sqrt((float *)msg) == (int)sqrt((float *)msg)*(int)sqrt((float *)msg))
        {
            printf("%i %n %f", cID, msg, sqrt((float *)msg));
        }
        N--;
    }
}

any ideas how to make this work?

Was it helpful?

Solution

msg is a pointer, and so is (float *)msg. Use *(float *)msg instead.

sqrt(*(float *)msg)

Howover, notice that you are not converting the int number into a float, you are reading msg as a float. Theres an important difference here, because the number 1 for instance, read as a float, is not 1.0f. If you want to convert the value of msg to float keeping it's int meaning, use (float)(*msg) instead.

sqrt((float)(*msg))

I'm not sure what mq_timedreceive() does so I don't know which one is correct for you, so you will have to figure that out yourself.

In addition, make sure you initialized the pointer int *msg before using it. I don't know if you did, sinse you omitted part of your code.

OTHER TIPS

if (sqrt(*msg) * sqrt(*msg) == (int)sqrt(*msg) * (int)sqrt(*msg))
    printf("%i %n %f", cID, msg, sqrt(*msg));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top