Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 将结构数组传递给pthread\u create_C++_Arrays_Pointers_Struct_Pthreads - Fatal编程技术网

C++ 将结构数组传递给pthread\u create

C++ 将结构数组传递给pthread\u create,c++,arrays,pointers,struct,pthreads,C++,Arrays,Pointers,Struct,Pthreads,我有一个结构如下: struct threadData{ string filename int one; int two; }; for(int i = 0; i < 5; i++){ pthread_create(&threadID[i], NULL, threadFunction, (void * ) threadP[i]); } 我创建了一个这样的结构数组: pthread_t threadID[5]; struct threadData

我有一个结构如下:

struct threadData{
    string filename
    int one;
    int two;
};
for(int i = 0; i < 5; i++){
    pthread_create(&threadID[i], NULL, threadFunction, (void * ) threadP[i]);
}
我创建了一个这样的结构数组:

pthread_t threadID[5];
struct threadData *threadP;
threadP = new struct threadData[5];
然后我将这个结构数组传递给一个线程函数,如下所示:

struct threadData{
    string filename
    int one;
    int two;
};
for(int i = 0; i < 5; i++){
    pthread_create(&threadID[i], NULL, threadFunction, (void * ) threadP[i]);
}
我尝试过各种方法,但我总是会遇到这样的错误:我传入的内容不正确,如何正确地执行此操作,以便访问和处理传入的每个struct对象中的变量?我有一种感觉,我的语法某处是错误的,因为我使用了一个数组的结构…我只是不知道哪里或什么地方是错误的。任何帮助都将不胜感激

void *threadFunction(void * threadP[]){

函数不能在C++中使用数组类型的参数,相反,参数必须是指针,而用作函数参数的数组会衰减到指向第一个元素的指针,因此声明等价于:

void *threadFunction(void ** threadP){
这显然不是传递给
pthread\u create

您需要传递具有此签名的函数:

void *threadFunction(void * threadP)

它应该是
&threadP[i]
。就这些。为什么不使用std::thread呢?看起来您的函数应该声明为
void*threadFunction(void*threadP)
,调用应该是
pthread\u create(&threadID[i],NULL,threadFunction,(void*)&threadP[i])看起来你的大部分抱怨都是风格上的。你暗示了真正的问题,但没怎么解释。这也有点误导,因为你不能把数组传递给C++中的函数。可以,但正如您所指出的,它们“衰减”为指针。但是,在某些情况下,实际上需要数组语法——例如在传递多维数组时。例如:。。。无论如何,多维数组与这种情况无关。不过,我只想指出,你的说法有点误导人,是否需要多加解释?函数的类型错误,这就是它无法编译的原因。当你有一个多维数组时,你仍然没有数组类型的参数,你有一个指向数组的指针。我已经删除了风格上的评论,并重新表述了答案