我正在使用C,我正在尝试传入一个指向数组的指针,该数组将保存我的线程ID,但我似乎无法使我的类型匹配。我不理解在C中传递指针的原因是什么?
这是我的功能:
int createThreads(int numThreads, pthread_t **tidarray) {
pthread_t *tids = *tidarray;
int i;
for (i = 0; i < numThreads; i++) {
pthread_create(tids + i, NULL, someFunction, NULL);
}
return 0;
}
这是我的电话:
pthread_t tids[numThreads];
createThreads(5, &tids);
当我编译它时,我收到一个警告: 从不兼容的指针类型传递'createThreads'的参数2,和 注意:预期'pthread_t **'但参数类型为'pthread_t(*)[(long unsigned int)(numThreads)]'
答案 0 :(得分:0)
#include <stdio.h>
#include <pthread.h>
// dummy function for threads , it just print its argument
void * someFunction(void *data){
printf("Thread %d\n",(int)data);
}
int createThreads(int numThreads, pthread_t *tidarray) {
int i;
for (i = 0; i < numThreads; i++) {
//pass the pointer of the first element + the offset i
pthread_create(tidarray+i, NULL, someFunction, (void*)i);
}
return 0;
}
int main(){
pthread_t tids[5]={0};// initialize all to zero
createThreads(5, tids);
getchar();// give time to threads to do their job
// proof-of-concept, the array has been filled by threads ID
for(int i=0;i<5;i++)
printf("Thread (%d) ID = %u\n",i,tids[i]);
return 0;
}
答案 1 :(得分:-1)
您不需要运营商的&
地址,只需将其原样传递,因为它会自动转换为指针,因此
createThreads(5, tids);
是您需要的,然后是您的createThreads()
功能
int createThreads(int numThreads, pthread_t *tids)
{
int i;
for (i = 0; i < numThreads; i++)
{
pthread_create(tids + i, NULL, someFunction, NULL);
}
return 0;
}