-1

I created a thread that should return a sqrt of integer sent to it, it works fine while returning int value, but when i want to return double or float value it returns some crazy numbers, how to change that?

Here's the code that works fine:

int* function(int* x) {

printf("My argument: %d \n", *x);
int *y = malloc(sizeof(int));
*y=sqrt(*x);
return y;
}

int main(int argc, char* argv[])
{
pthread_t thread;
int arg = 123;
int *retVal;


pthread_create(&thread, NULL, (void * ( * ) (void *))function, &arg);

pthread_join(thread, (void **) &retVal);
printf("Sqrt of our argument: %d\n", * retVal);
free(retVal);
return 0;

}

But when I change it into:

double* function(int* x) {


double *y = malloc(sizeof(double));
*y=sqrt(*x);
printf("My argument: %d \n", *x);
return y;
}

int main(int argc, char* argv[])
{
pthread_t thread;
int arg = 123;
double *retVal;


pthread_create(&thread, NULL, (void * ( * ) (void *))function, &arg);

pthread_join(thread, (void **) &retVal);
printf("Sqrt of our argument: %d\n", * retVal);
free(retVal);
return 0;
}

It returns 1076244058

alk
  • 69,737
  • 10
  • 105
  • 255
MaciekB
  • 51
  • 1
  • 7

1 Answers1

3

Your change is wrong

printf("Sqrt of our argument: %d\n", * retVal);

must be

printf("Sqrt of our argument: %f\n", * retVal);

I guess your compiler is telling you something like

warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘double *’ [-Wformat=]

BTW your implementation invokes undefined behavior casting function: take a look at this SO answer

As already suggested you can use arg to pass the value back to main instead of return it from task function.

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

void* function(void* x)
{
    double *y = x;

    *y = sqrt(*y);

    return x;
}

int main(void)
{
    pthread_t thread;
    double arg = 123;
    void *retVal = NULL;

    pthread_create(&thread, NULL, function, &arg);

    pthread_join(thread, &retVal);
    printf("Sqrt of our argument using arg   : %f\n", arg);

    if (retVal != NULL)
    {
        printf("Sqrt of our argument using retVal: %f\n", *((double *)retVal));
    }

    return 0;
}
Community
  • 1
  • 1
LPs
  • 16,045
  • 8
  • 30
  • 61