我需要將多個參數傳遞給要在單獨線程上調用的函數。我已經讀到,執行此操作的典型方法是定義一個struct,向該函數傳遞一個指向該struct的指針,然后將其取消引用以用作參數。但是,我無法使它正常工作:#include <stdio.h>#include <pthread.h>struct arg_struct { int arg1; int arg2;};void *print_the_arguments(void *arguments){ struct arg_struct *args = (struct arg_struct *)args; printf("%d\n", args -> arg1); printf("%d\n", args -> arg2); pthread_exit(NULL); return NULL;}int main(){ pthread_t some_thread; struct arg_struct args; args.arg1 = 5; args.arg2 = 7; if (pthread_create(&some_thread, NULL, &print_the_arguments, (void *)&args) != 0) { printf("Uh-oh!\n"); return -1; } return pthread_join(some_thread, NULL); /* Wait until thread is finished */}輸出應為:57但是當我運行它時,我實際上得到了:141921115-1947974263有人知道我在做什么錯嗎?
3 回答

神不在的星期二
TA貢獻1963條經驗 獲得超6個贊
因為你說
struct arg_struct *args = (struct arg_struct *)args;
代替
struct arg_struct *args = arguments;

米琪卡哇伊
TA貢獻1998條經驗 獲得超6個贊
使用
struct arg_struct *args = (struct arg_struct *)arguments;
代替
struct arg_struct *args = (struct arg_struct *)args;

呼喚遠方
TA貢獻1856條經驗 獲得超11個贊
main()有自己的線程和堆棧變量。為堆中的“ args”分配內存或使其成為全局內存:
struct arg_struct {
int arg1;
int arg2;
}args;
//declares args as global out of main()
然后,當然,改變從引用args->arg1到args.arg1等。
- 3 回答
- 0 關注
- 655 瀏覽
添加回答
舉報
0/150
提交
取消