gpt4 book ai didi

在 C 中复制对数组的引用

转载 作者:行者123 更新时间:2023-11-30 16:53:15 27 4
gpt4 key购买 nike

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

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

enter image description here

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;
}

最佳答案

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

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

此外,您似乎还没有初始化 number_of_files ;不要忘记,如果您的代码实际上使用了它。

关于在 C 中复制对数组的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40954858/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com