LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 821|回复: 7

void 与指针问题求助!

[复制链接]
发表于 2004-11-3 23:28:41 | 显示全部楼层 |阅读模式
(void *) *arg 和 (void *) arg

(void *) &lot 和 (void *) lot

以上几个有何区别!!:help
发表于 2004-11-4 11:52:51 | 显示全部楼层
arg和lot是什么类型?!!
 楼主| 发表于 2004-11-4 17:44:11 | 显示全部楼层
lot是 int 类型,arg 好像是 void类型!

更正:
(void *) *arg 和 (void *) arg 应该为  *(void *)arg 和 (void *) arg

整个程序是:


  1. #include <stdio.h>
  2. #include <unistd.h>
  3. #include <stdlib.h>
  4. #include <pthread.h>

  5. #define NUM_THREADS 6

  6. void *thread_function(void *arg);

  7. int main(void)
  8. {
  9.         int res, lots_of_threads;
  10.         pthread_t a_thread[NUM_THREADS];
  11.         void *thread_result;

  12.         for(lots_of_threads = 0; lots_of_threads < NUM_THREADS; lots_of_threads++)
  13.         {
  14.                 res = pthread_create(&(a_thread[lots_of_threads]), NULL, thread_function,
  15. [color=red](void *)lots_of_threads[/color]);

  16.                 if(res != 0)
  17.                 {
  18.                         perror("phtread create failed\n");
  19.                         exit(EXIT_FAILURE);
  20.                 }
  21.                 sleep(1);
  22.         }

  23.         printf("Waiting for threads of finish...\n");
  24.         for(lots_of_threads = NUM_THREADS - 1; lots_of_threads >= 0; lots_of_threads--)
  25.         {
  26.                 res = pthread_join(a_thread[lots_of_threads], &thread_result);
  27.                 if(res == 0)
  28.                 {
  29.                         printf("Picked up a thread\n");
  30.                 }
  31.                 else
  32.                 {
  33.                         perror("pthread_join failed\n");
  34.                 }
  35.         }
  36.         printf("All done\n");

  37. return 0;
  38. }

  39. void *thread_function(void *arg)
  40. {
  41.         [color=red]int my_number = (int )arg;[/color]
  42.         int rand_num;

  43.         printf("thread_function is runing. Argument was %d\n", my_number);
  44.         rand_num = 1 + (int)(9.0*rand() / (RAND_MAX+1.0));
  45.         sleep(rand_num);
  46.         printf("Bye form %d\n", my_number);

  47.         pthread_exit(NULL);
  48. }

复制代码


看到书上说把(void *)&lots_of_threads,*(int *)arg改为红字部分可以解决某些问题
发表于 2004-11-4 19:26:31 | 显示全部楼层
lot是整形,那么(void *)lot就是将lot这个整数的值强制类型转换为一个地址。而&lot是取lot的地址,(void *) &lot则是将取到的地址再强制转换为void类型。
 楼主| 发表于 2004-11-5 12:44:13 | 显示全部楼层
最初由 kj501 发表
lot是整形,那么(void *)lot就是将lot这个整数的值强制类型转换为一个地址。而&lot是取lot的地址,(void *) &lot则是将取到的地址再强制转换为void类型。


(void *) &lot按运算符先后顺序的话,应该是先(void *)运算后再取地址(&)吧?
发表于 2004-11-5 14:27:43 | 显示全部楼层
最初由 含笑半步跌 发表
(void *) &lot按运算符先后顺序的话,应该是先(void *)运算后再取地址(&)吧?


怎么可能呢
发表于 2004-11-5 17:16:04 | 显示全部楼层
最初由 含笑半步跌 发表
(void *) &lot按运算符先后顺序的话,应该是先(void *)运算后再取地址(&)吧?

你把(void *) &lot看着是(void *) (&lot)就好理解了。
 楼主| 发表于 2004-11-5 17:48:20 | 显示全部楼层
大概明白了:p
您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表