[英]Passing array pointer into function in C
我正在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) ]'
#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;
}
您不需要運算符的&
地址,只需按原樣傳遞它,因為它會自動轉換為指針,因此
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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.