在C语言中将数组指针传递给函数
我在C语言中工作,我试图传入一个指向数组的指针,该数组将保存我的线程ID,但我似乎无法使我的类型匹配。我对C语言中传递指针有什么不理解 这是我的职责:在C语言中将数组指针传递给函数,c,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
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;
}
当我编译这个时,我得到一个警告:
从不兼容的指针类型传递“createThreads”的参数2,以及
注意:应为“pthread\u t**”,但参数的类型为“pthread\u t(*)(长无符号int)(numThreads)]”您不需要运算符的
&
地址,只需按原样传递它,因为它会自动转换为指针,所以
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;
}
int-createThreads(int-numThreads,pthread\u t*tids)
{
int i;
对于(i=0;i
#包括
#包括
//线程的伪函数,它只打印其参数
void*someFunction(void*data){
printf(“线程%d\n”,(int)数据);
}
int createThreads(int numThreads,pthread\u t*tidarray){
int i;
对于(i=0;i 对于(int i=0;iIt,看起来您希望参数是pthread\u t*
,而不是**
tidary
不是数组指针,而是指向指针的指针。数组指针应该是pthread\u t(*tidarray)[numThreads]
,正如错误消息所建议的。虽然此代码可能会回答问题,但最好在不介绍其他人的情况下解释它如何解决问题以及为什么使用它。从长远来看,仅使用代码的答案是没有用的。@JAL,\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu。
int createThreads(int numThreads, pthread_t *tids)
{
int i;
for (i = 0; i < numThreads; i++)
{
pthread_create(tids + i, NULL, someFunction, NULL);
}
return 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;
}