-2

I'm writing a C/C++ code to practice PThreads. I'm working off my instructor's example. I'm getting an error. I don't know how to proceed. The error is: Invalid conversion from ‘void*’ to ‘pthread_t*’, and it is caused by the malloc line.

I left some code out. thread_count is a global variable, and its value is captured at the command line.

#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)); 
}
Baum mit Augen
  • 49,044
  • 25
  • 144
  • 182

1 Answers1

1

You need to explicitly convert the pointer returned from malloc to the correct type:

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

malloc doesn't returned properly-typed pointers, because it doesn't know what type you want. It returns void*. C++ won't allow you to assign a void* to a differently-typed variable unless you explicitly cast it to the correct type.

Daniel Eisener
  • 323
  • 1
  • 4