【问题标题】:Copy reference to array in C在C中复制对数组的引用
【发布时间】:2016-12-04 02:51:33
【问题描述】:

我正在尝试获取一个字符串数组 (char*) 并将它们平均划分,以便线程可以对其进行操作。我在想,理论上,我可以创建一个指向文件名数组中某个位置的引用的结构。我提供了一个小图形来解释它,但在下面的代码中,我想要做的是每 40 个文件名并插入它进入成员结构(结构数组)。我知道这有点令人困惑,但请告诉我是否有任何方法可以澄清它。

我希望我的代码生成 t 数组,并引用文件名中的偏移位置,我将如何处理它,因为在当前状态下,编译器不允许 t[i].files = filenames[incr];

typedef struct divided_files{
    char** files;
    int number_of_files;
} struct_struct;

int threads = 8;
struct_struct* t = malloc(threads*sizeof(struct_struct));
char* filenames[320]; //imagine it's populated with strings

int i;
int offset = 40;
int incr = 0;
for(i = 0 ; i < threads; i++){
     t[i].files = filenames[incr];
     incr += offset;
}

【问题讨论】:

  • 这里有问题吗?到目前为止,您似乎可以很好地划分您的 320 个字符串,尽管您可能想要设置 number_of_files。您是否担心您没有确切的 320 个文件,并且想要平均划分它们?
  • 如果 OP 发布了编译器错误,那会更明显...... @asdasda
  • 我确保在最近的编辑中澄清

标签: c arrays multithreading multidimensional-array struct


【解决方案1】:

您的代码看起来就像您想要的那样——将数组划分,给每个线程 40——除了一个小的变化。要获取指向数组偏移量的指针,请将偏移量直接添加到数组指针中:

t[i].files = filenames + incr; // pointer arithmetic to get an offset pointer

另外,您似乎要离开 number_of_files 未初始化;如果您的代码实际使用它,请不要忘记这一点。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-14
    • 1970-01-01
    • 2021-12-09
    • 1970-01-01
    • 2017-05-16
    • 1970-01-01
    • 2016-11-02
    相关资源
    最近更新 更多