从内存的角度来看,将整数值转换为void*
或反之亦然? 我的理解是void*
是未指定长度的内存块的地址。
这似乎是比较苹果和橙子。将int转换为void *或反之亦然?
int myval = 5;
void* ptr = (void*)myval;
printf("%d",(int)ptr);
我意识到我应该给出确切的上下文,在这里使用它。
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 */
此代码来自Peter Pachecho的关于并行编程的书。
可能的重复:http://stackoverflow.com/questions/3568069/is-it-safe-to-cast-an-int-to-void-pointer-and-back-to-int-again –
它是更糟糕的是 - 至少像比较苹果和土豆 – alk