我正在從書中調試程序。該程序似乎工作,但我不明白下面我評論的一條線。爲什麼這個投射無效指針有效?
#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;
}
我會返回這本書:)這確實是一個黑客,雖然是一個常見的(指針中存儲值,取決於相同類型的寬度)。 – nielsj
POSIX似乎支持這種黑客攻擊:例如'SIG_IGN'。 –
@Joseph Quinsey我知道;我也讀了R ..的答案,我同意。儘管如此,親自使用太難看了。 – cnicutar