Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/62.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 如何将具有参数的函数指针作为另一个函数的参数传递?_C - Fatal编程技术网

C 如何将具有参数的函数指针作为另一个函数的参数传递?

C 如何将具有参数的函数指针作为另一个函数的参数传递?,c,C,如您所见,我想将函数send_message传递给pthread_create,但我不知道如何传递它的参数。如何做到这一点 pthread_create(&t_write, NULL, send_message, NULL); // how to specify argument of the send_message? void *send_message(void *sockfd){ char buf[MAXLEN]; int *fd = (int *)sockf

如您所见,我想将函数
send_message
传递给
pthread_create
,但我不知道如何传递它的参数。如何做到这一点

pthread_create(&t_write, NULL, send_message, NULL); // how to specify argument of the send_message?

void *send_message(void *sockfd){

    char buf[MAXLEN];
    int *fd = (int *)sockfd;
    fgets(buf, sizeof buf, stdin);

    if(send(*fd, buf, sizeof buf, 0) == -1){
        printf("cannot send message to socket %i\n", *fd);
        return (void *)1;
    }

    return NULL;
}

简短回答:只需将参数作为第四个参数传递给
pthread\u create

详细回答:
pthread\u create
的定义如下(根据手册页):

int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
                      void *(*start_routine) (void *), void *arg);
第三个参数的含义可以用
cdecl
解码:

cdecl> explain void *(*start_routine) (void *)
declare start_routine as pointer to function (pointer to void) returning pointer to void
如您所见,它需要一个指向函数的指针,该函数接受
void*
并返回
void*
。幸运的是,这正是你所拥有的。根据
pthread\u create
的手册页:

新线程通过调用
start_routine()
开始执行
arg
作为
start\u routine()
的唯一参数传递


您是否查看过库函数
qsort()
以了解传递函数参数是如何实现的?