2017-11-27 4 views
0

私はcppとスレッドの初心者です。 stackoverflowのいくつかのコードスニペットを参照して、複数の引数をpthread関数に渡し、以下のコードを思いついた。私はそれに渡された(void *)ポインタを使って関数内の構造体メンバにアクセスする方法がわかりません。誰でも説明できますか?pthread関数への複数のパラメータの受け渡しとアクセス

#include <iostream> 
#include <pthread.h> 
#include <vector> 
using namespace std; 

struct a{ 
vector <int> v1; 
int val; 
}; 

void* function(void *args) 
{ 
vector <int>functionvector = (vector <int>)args->v1; 
functionvector.push_back(args->val); 
return NULL; 
} 


int main() 
{ 
    pthread_t thread; 
    struct a args; 

    pthread_create(&thread, NULL, &function, (void *)&args); 
    pthread_join(thread,NULL); 
    for(auto it : args.v1) 
    { 
    cout<<it; 
    } 

    return 0; 
} 

エラーを取得: エラー:「無効*」をされていないポインタとオブジェクトタイプ

+0

キャスト元のタイプにキャストし直す必要があります。 '&args'は' a * 'です。 – molbdnilo

+0

pthreadsではなくstd :: threadを使用します。 –

答えて

1

あなたはa*に戻ってvoid*をキャストするまで、あなたがaのメンバーにアクセスすることはできません。

void* function(void *ptr) 
{ 
a* args = static_cast<a*>(ptr); 

args->v1.push_back(args->val); 
return NULL; 
} 
+0

おっと!とった!ありがとう。 – newbie

関連する問題