大佬教程收集整理的这篇文章主要介绍了将结构作为void指针传递给函数,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
typedef struct { pthread_t tID; int tType; }sThread; sThread threads[MAX_THREADS]; typedef struct { int tID; int sock; int arg_count; char *from_p,**arg_p; }command_struct; pthread_t Thread_Start(void *function,void *param) { pthread_t tHandle; pthread_create(&tHandle,NULL,function,(void*)param); return tHandle; } void cmd_test(int sock,char *from_p,char **arg_p,int arg_count) { if(thread_check(1)) { send_line(sock,"%s :test thread already running",from_p); return; } command_struct test; test.tID = thread_add(1); test.arg_count = arg_count; test.arg_p = arg_p; threads[test.tID].tID = Thread_Start(test_cmd,&test); } void *test_cmd(void *param) { command_struct test = *((command_struct *)param); int i = 0; for(i = 1; i < test.arg_count; i++) { printf("%s",test.arg_p[i]); } thread_clear(test.tID); return NULL; }
发生的事情是cmd_test(产生线程的函数)内部结构被正确初始化并且所有变量都是正确的.
$1 = {tID = 0,sock = 5,arg_count = 5,from_p = 0xbffff254 "test",arg_p = 0xbfffec48}
但是,如果在运行的线程内部使用test_cmd,则结构缺少arg_p的地址1个字节,导致:
$1 = {tID = 0,arg_p = 0xffec48}
如果我在command_struct arg_p的地址末尾添加一个无用的变量然后变得正确,并且command_struct中的最后一个变量缺少1个字节的内存地址.
试试这个:
void cmd_test(int sock,int arg_count) { if(thread_check(1)) { send_line(sock,from_p); return; } // === begin modified code in cmd_test(): command_struct* test = malloc(sizeof(command_struct)); test->tID = thread_add(1); test->arg_count = arg_count; test->arg_p = arg_p; threads[test.tID].tID = Thread_Start(test_cmd,test); // === end modified code } void *test_cmd(void *param) { command_struct test = *((command_struct *)param); free(param); // <-- new line of code // remainder is the same... // ... }
以上是大佬教程为你收集整理的将结构作为void指针传递给函数全部内容,希望文章能够帮你解决将结构作为void指针传递给函数所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。