0

i have a code in c++ file in and got an error

void* sample(void* ar[]){
   struct test *b=(struct test*) ar
   //some code
   return NULL;
}

The main:

int main(int argc,char** argv){
   struct test{
     int a;
     int b;
   }
   int max=2;
   pthread_t pid[max];
   struct test ar[max];
     ar[0].a=1;
     ar[0].b=2;
     ar[1].a=3;
     ar[1].b=4;
   for(int i=0;i<max;i++){
     pthread_create(&pid[i],NULL,sample,&ar[i]);
   }
   return 0;
}

When i compile, it show me an error like this:

The error

hyde
  • 60,639
  • 21
  • 115
  • 176
TatGiaVi
  • 3
  • 3
  • 4
    any reason you aren't using `std::thread` which avoids needing to use `void*`? the function passed to `pthread_create` must have a single `void*` argument – Alan Birtles Oct 21 '22 at 07:07
  • 3
    As an argument, `void* ar[]` is the same as `void **ar`. Which is the incorrect type for thread functions. Its argument should be `void *`, as in `void *ar`. Who told you to use `void *ar[]`? – Some programmer dude Oct 21 '22 at 07:07
  • your `sample` function takes double pointer (`void **ar`), you are passing it address of a single `struct test`. Try fixing this first. – hyde Oct 21 '22 at 07:08
  • Please don't use images of error messages. Using text allows you to (hint!) search for the error message to get info. Also, take the [tour] and read [ask]. – Ulrich Eckhardt Oct 21 '22 at 07:08
  • Any particular reason why is posting an image of text better than posting the text itself? – Quimby Oct 21 '22 at 07:08
  • 3
    Are you sure this code is intended to be C++? It looks more like C, not only because of the use of pthreads, but also since there are e.g. `struct` keywords that are redundant in C++, use of `NULL` instead of `nullptr`, and variable-length arrays. – user17732522 Oct 21 '22 at 07:11
  • Note that variable-length arrays (VLAs) are not part of the C++ standard. They're a compiler extension. – JHBonarius Oct 21 '22 at 07:24
  • Side note, before you dive into multithreading you might first brush up on your C++. It is still more "C" then "C++". The use of void* is just not necessary. For C++ use std::async and learn about std::vector, lambda functions and captures, std::mutex and possibly std::shared_ptr (if you want to share data between threads with unknown or unpredictable life cycle). Since C++11 you shouldn't have to use pthreads. – Pepijn Kramer Oct 21 '22 at 07:29
  • Here is what the C++ equivalent would look like : https://onlinegdb.com/w_juViuu1 (I named your struct sample, and your sample function f) – Pepijn Kramer Oct 21 '22 at 07:44

0 Answers0