从“ void*”到“ pthread_t*”的无效转换

Invalid conversion from ‘void*’ to ‘pthread_t*’

本文关键字:无效 转换 void pthread      更新时间:2023-10-16

我正在编写c/c 代码练习pthreads。我正在努力工作的榜样。我有一个错误。我不知道该如何进行。错误是:从" void*"转换为" pthread_t*",它是由malloc线引起的。

我遗漏了一些代码。thread_count是一个全局变量,其值在命令行中捕获。

#include <cstdlib>
#include <cstdio>
#include <sys/time.h>
#include <pthread.h>
int main(int argc, char *argv[])
{
   // this is segment of my code causing error
   // doesn't like the third line of code 
   static long thread; 
   pthread_t* thread_handles;
   thread_handles = malloc(thread_count*sizeof(pthread_t)); 
}

您需要将从malloc返回的指针明确转换为正确的类型:

static long thread; 
pthread_t* thread_handles;
thread_handles = (pthread_t*)malloc(thread_count*sizeof(pthread_t));

malloc没有返回正确的指针,因为它不知道您想要什么类型。它返回void*。C 不允许您将void*分配给不同类型的变量,除非您将其明确施放为正确的类型。