为什么这个转换为无效指针有效?

2 c pointers casting void

我正在调试一本书中的程序.该程序似乎工作,但我不明白我在下面评论的一行.

#include <pthread.h>
#include <stdio.h>
/* Compute successive prime numbers (very inefficiently). Return the
Nth prime number, where N is the value pointed to by *ARG. */
void* compute_prime (void* arg)
{
int candidate = 2;
int n = *((int*) arg);
while (1) {
int factor;
int is_prime = 1;
/* Test primality by successive division. */
for (factor = 2; factor < candidate; ++factor)
if (candidate % factor == 0) {
is_prime = 0;
break;
}
/* Is this the prime number we’re looking for? */
if (is_prime) {
if (--n == 0)
/* Return the desired prime number as the thread return value. */
return (void*) candidate;    // why is this casting valid? (candidate is not even a pointer)
}
++candidate;

}
return NULL;
}
int main ()
{
pthread_t thread;
int which_prime = 5000;
int prime;
/* Start the computing thread, up to the 5,000th prime number. */
pthread_create (&thread, NULL, &compute_prime, &which_prime);
/* Do some other work here... */
/* Wait for the prime number thread to complete, and get the result. */
pthread_join (thread, (void*) &prime);
/* Print the largest prime it computed. */
printf(“The %dth prime number is %d.\n”, which_prime, prime);
return 0;
}
Run Code Online (Sandbox Code Playgroud)

cni*_*tar 5

它无效.如果sizeof(int) == sizeof(void *)发生在许多系统上,它恰好会起作用.

A void *只能保证能够保存指向数据对象的指针.

这是关于这个主题的C FAQ.

如何将整数转换为指针和从指针转换?我可以暂时将整数填充到指针中,反之亦然吗?

指针到整数和整数到指针的转换是实现定义的(参见问题11.33),并且不再保证指针可以转换为整数并返回,而无需更改

强制指针整数或整数指针,从来都不是一个好习惯