c - 为什么这个转换为 void 指针有效?

标签 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;
}

最佳答案

这是无效的。如果 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/

相关文章:

c++ - 用于多态性的引用和指针?

c - 冒泡排序到 char 指针

excel在计算单元格数量时指向单元格

java - 在 Java 中将实数转换为 Comparable?

java - SWIG从String作为Java中的String数组获取returntype

c - 如何使用最少数量的赋值运算符构建 OneTwoThree 链表?

parameters - 类型转换为自定义对象 - 数据丢失吗?

delphi - 将 SmallInt 常量定义为十六进制

在 C 中使用较少数量的参数调用函数?

c++ - C/C++ 中超大静态数组的算术运算