我正在调试书中的一个程序。该程序似乎可以工作,但我不明白我在下面评论的一行。
#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;
}
最佳答案
这是无效的。如果 sizeof(int) == sizeof(void *)
,它只是碰巧起作用,这在许多系统上都会发生。
void *
只能保证能够保存指向数据对象的指针。
这是一个C FAQ关于这个问题。
How are integers converted to and from pointers? Can I temporarily stuff an integer into a pointer, or vice versa?
Pointer-to-integer and integer-to-pointer conversions are implementation-defined (see question 11.33), and there is no longer any guarantee that pointers can be converted to integers and back, without change
Forcing pointers into integers, or integers into pointers, has never been good practice
关于c - 为什么这个转换为 void 指针有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6889568/