#include <pthread.h>
#include "../header/tlpi_hdr.h"
static void *
threadFunc(void *arg)
{
char *s = (char *) arg;
printf("%s", s);
return (void *) strlen(s);
}
int
main(int argc, char *argv[])
{
pthread_t t1;
void *res;
int s;
s = pthread_create(&t1, NULL, threadFunc, "Hello world\n");
if (s != 0)
errExitEN(s, "pthread_create");
printf("Message from main()\n");
s = pthread_join(t1, &res);
if (s != 0)
errExitEN(s, "pthread_join");
printf("Thread returned %ld\n", (long) res);
exit(EXIT_SUCCESS);
}
上面的代码是我现在正在研究的,但是我不明白数据类型的转换。
在threadFunc()
上,返回类型为void *
。但从这个函数来看,strlen(s)
的类型是size_t
。但如何将其更改为 (void *)
。我的意思是,为什么不 (void *) &strlen(s)
?
并且,也在 main()
中,有 printf("Thread returned %ld\n", (long) res);
。
由此可见,变量 res
的类型是 (void *)
,而不是 int
或 long
。所以,应该这样修改:
(长)*res
。
但是,如何将其更改为(long) res
?
最佳答案
But how this can be changed to
(void *)
. I mean, why not(void *) &strlen(s)
(?)
strlen()
的返回类型是size_t
,某种无符号整数类型。将任意整数值转换为 void*
是未定义行为 (UB)。
return (void *) strlen(s); // Undefined behavior
代码可以将长度保存在某处,例如静态/全局或分配的内存中并返回地址。我怀疑这是否能满足 OP 的其他编码目标。
static size_t len = 0;
len = strlen(s);
return (void *) &len;
strlen()
的返回值 1) 不能用 &strlen(...)
获取其地址 2) 即使语言允许,代码仍然需要考虑指针的生命周期。
how this can be changed to (long) res?
调用代码将返回的指针解释为相同类型以防止 UB 非常重要。
void *res;
...
s = pthread_join(t1, &res);
if (s != 0) {
errExitEN(s, "pthread_join");
}
if (res != NULL)
size_t *len_ptr = (size_t*) res;
printf("Thread returned %zu\n", *len_ptr);
// or if long is truly needed
long len_as_long = (long) *len_ptr;
printf("Thread returned %ld\n", len_as_long);
}
关于c - C中的数据类型转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38692293/