我创建了一个线程,它应该返回一个发送给它的sqrt整数,它在返回int值时工作正常,但是当我想返回double或float值时,它会返回一些疯狂的数字,如何改变它?
以下是可行的代码:
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;
}
但是当我把它变成:
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;
}
它返回1076244058
答案 0 :(得分:4)
你的改变是错误的
printf("Sqrt of our argument: %d\n", * retVal);
必须是
printf("Sqrt of our argument: %f\n", * retVal);
我猜您的编译器会告诉您类似
的内容warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘double *’ [-Wformat=]
BTW你的实现会调用未定义的行为转换函数:看看this SO answer
如前所述,您可以使用arg
将值传回main
,而不是从任务函数返回。
#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;
}