【问题标题】:Invalid conversion from ‘void*’ to ‘pthread_t*’ [duplicate]从“void*”到“pthread_t*”的无效转换[重复]
【发布时间】:2017-03-07 02:50:36
【问题描述】:

我正在编写 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)); 
}

【问题讨论】:

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

标签: c++ parallel-processing pthreads


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 2017-06-30
    • 2019-03-15
    • 2013-08-19
    • 1970-01-01
    • 1970-01-01
    • 2010-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多