void*从内存的角度来看,将整数值转换为或者反之亦然?我的理解是void*一个未指定长度的内存块的地址.
这似乎就像比较苹果和橙子.
int myval = 5;
void* ptr = (void*)myval;
printf("%d",(int)ptr);
Run Code Online (Sandbox Code Playgroud)
我意识到我应该给出使用它的确切上下文.
int main(int argc, char* argv[]) {
long thread; /* Use long in case of a 64-bit system */
pthread_t* thread_handles;
/* Get number of threads from command line */
if (argc != 2) Usage(argv[0]);
thread_count = strtol(argv[1], NULL, 10);
if (thread_count <= 0 || thread_count > MAX_THREADS) Usage(argv[0]);
thread_handles = malloc (thread_count*sizeof(pthread_t));
for (thread = 0; thread < thread_count; thread++)
pthread_create(&thread_handles[thread], NULL, Hello, (void*) thread);
printf("Hello from the main thread\n");
for (thread = 0; thread < thread_count; thread++)
pthread_join(thread_handles[thread], NULL);
free(thread_handles);
return 0;
} /* main */
/*-------------------------------------------------------------------*/
void *Hello(void* rank) {
long my_rank = (long) rank; /* Use long in case of 64-bit system */
printf("Hello from thread %ld of %d\n", my_rank, thread_count);
return NULL;
} /* Hello */
Run Code Online (Sandbox Code Playgroud)
这段代码来自Peter Pachecho关于并行编程的书.
bob*_*mcr 20
转换int为void *没有意义,不应该像你试图将非指针强制转换为指针一样.引用C99标准,第6.3.2.3节第5项:
整数可以转换为任何指针类型.除非先前指定,否则结果是实现定义的,可能未正确对齐,可能不指向引用类型的实体,并且可能是陷阱表示.
你可以施放int *到void *(任何指针可以转换为void *这你能想到的像所有指针的"基地型").
铸造void *到int是不可移植的,并且可以根据您使用(例如,在平台上是完全错误的void *,也许64个位宽,并int可能只有32位).再次引用C99标准,第6.3.2.3节第6项:
任何指针类型都可以转换为整数类型.除非先前指定,否则结果是实现定义的.如果结果无法以整数类型表示,则行为未定义.结果不必在任何整数类型的值范围内.
为了解决这个问题,一些平台提供uintptr_t了允许您将指针视为适当宽度的数值的方法.