c - 如何从传递给线程函数的参数数组中获取字符指针?

标签 c pointers pthreads

我不知道如何访问 args 中包含的字符指针。 args 是传递给 pthread_create 的字符点数组。我应该将参数存储在结构体而不是数组中吗?

int loop(void* args){
  struct dirent *direntp; DIR *start_dir;struct stat statbuf;char *dirs[MAX_SIZE_DIRS];int error; const char* sd;
  int size = 0;
  char* fn = (char *)(args); sd = (char *)(args + 1); char* path = (char *)(args+2);
  printf("%s\n", (char *)args);

最佳答案

也许你想要:

int loop(void* args){
  char** arr = args;
  char* fn = arr[0];
  char* sd = arr[1];
  char* path = arr[2];

(事实上,出于可读性的原因,最好在线程函数之外声明一些struct并使用它的地址,因为不同的元素具有不同的角色)

在尝试编写多线程程序之前,您应该花几天时间阅读一本好的 C 编程书籍(例如使用 POSIX threads )。

顺便说一句,函数传递给 pthread_create(3)应该返回一个通用指针(即一些 void*),而不是 int;所以你的loop有错误的签名传递给pthread_create。另请阅读 intptr_t

关于c - 如何从传递给线程函数的参数数组中获取字符指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34305337/

相关文章:

c - C语言的黄金比例?

c - 将命令行语句解析为标记列表

c - 函数执行后结构保持不变

c++ - void指针函数的使用

c - 我如何用C中的线程对数组元素求和?

c# - 为什么 C 和 C++ 中的 float / double 没有除余运算?

c - 数组中需要左值错误

macos - 在Mac OS X上的pthread_specific()中崩溃

C++ 定时进程

c - 将节点添加到链表中的随机位置