*((int *) arg)

本文介绍了在多线程编程中,如何使用void指针进行类型转换以传递参数。示例展示了将void指针转换为int类型和char类型,分别用于传递整数和字符串,并在目标函数中正确解析和输出。这种做法在跨平台编程和库函数中常见,允许函数接收不同类型的参数。
摘要由CSDN通过智能技术生成

(1)在函数threadFunc中,它被声明为具有void *类型,而不是int *类型

 void *threadFunc(void *arg)
{
   int loops = *((int *) arg);
   printf("the loops value is %d \n",loops);
}

(2)因此,在这个表达式中

int loops = *((int *) arg);

(3)该指针最初再次解释为int *类型的指针,也就是将void类型的指针强制转换为int类型指针。

(int *) arg

(4)然后,它被解除引用,以获得它所指向的对象。

*((int *) arg)

示例1:

 #include<stdlib.h>
 #include<stdio.h>
 #include<unistd.h>
 #include<pthread.h>
 #include<string.h>
 
 void *threadFunc(void *arg)
{
   int loops = *((int *) arg);
   printf("the loops value is %d \n",loops);
}

int main(void )
{
   pthread_t t1;
   int  s=100;
    void *thread_result;
    
   s = pthread_create(&t1, NULL, threadFunc, &s);
   
   pthread_join(t1,thread_result);
   exit(0);
  
}
   s = pthread_create(&t1, NULL, threadFunc, &s); &s向 threadFunc传递的是整型实参,但是threadFunc中的形参是void指针。在threadFunc中通过将void指针转换为int类型。结果输出的是整型值。

示例2:将void 类型支撑转换为char类型。输出 的结果为Hello World

 #include<stdlib.h>
 #include<stdio.h>
 #include<unistd.h>
 #include<pthread.h>
 #include<string.h>
 
 void *threadFunc(void *arg)
{
   char* loops = ((char *) arg);
   printf("the value of loops is \n");
   puts(loops);
}

int main(void )
{
   pthread_t t1;
   char *  s="Hello World \n";
	void *thread_result;

    pthread_create(&t1, NULL, threadFunc, s);
   
   pthread_join(t1,thread_result);
   
   exit(0);
   
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值