2017-03-07 253 views
-2

我正在写一个C/C++代码来练习PThreads。我正在训练我的教练的例子。我收到一个错误。我不知道如何继续。错误是:从'void *'到'pthread_t *'的转换无效,并且是由malloc行引起的。无效的从'void *'转换为'pthread_t *'

我遗漏了一些代码。 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)); 
} 
+1

C或C++,选择一种语言。他们是不同的语言。 –

回答

0

你需要明确将从malloc返回到正确的类型指针:

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

malloc不正确返回类型的指针,因为它不知道你想要什么类型。它返回void*。除非明确地将其转换为正确的类型,否则C++不允许将void*分配给不同类型的变量。

相关问题