【问题标题】:How do I get the character pointers out of the argument array passed to my thread function?如何从传递给我的线程函数的参数数组中获取字符指针?
【发布时间】:2015-12-16 06:31:59
【问题描述】:

我不知道如何访问 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);

【问题讨论】:

    标签: c pointers pthreads


    【解决方案1】:

    也许你想要:

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

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

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

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

    【讨论】:

      猜你喜欢
      • 2013-04-25
      • 1970-01-01
      • 1970-01-01
      • 2012-11-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-20
      • 1970-01-01
      相关资源
      最近更新 更多