gpt4 book ai didi

C memcpy 未按预期运行

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

此问题与 Making an Array to Hold Arrays of Character Arrays in C 相关。

从那里借用代码,我有一些看起来像这样的东西(感谢 luser droog 提供了很好的示例代码):

enum { BUFSZ = 50 };
enum { STRVSZ = 40 };
enum { STRVVSZ = 20 };
char buf[BUFSZ + 1];
char *strv[STRVSZ + 1];
char **strvv[STRVVSZ + 1];

int j;
int i;

while(1){
fgets(buf, BUFSZ, infile);

i = 0;
strv[i] = strdup(buf);
strv[i+1] = NULL;

j = 0;
strvv[j] = calloc(i+1, sizeof *strvv[j]); // assuming i is the count of elements
memcpy(strvv[j], strv, i * sizeof *strvv[j]);
j++;
}

这可能不会立即运行,但它说明了与我正在运行的类似的情况。基本上,每次循环迭代后,strv 的内容都需要存储在 strvv 中,并且 strv 根据用户输入随时间变化。

使用 calloc 和 memcpy 应该会导致 strvv 在循环的每次迭代中维护 strv 的副本,而与 strv 中的值无关。但是,当我打印出 strvv 的内容时,它为每个条目打印出相同的字符串,这意味着当前的方法仍在移动指针,而不是在每个 strvv 条目中复制 strv。

我完全不确定为什么会发生这种情况或如何解决它。 memcpy 应该对 strv 中的指针指向的内容进行字节级复制 =/。

最佳答案

这更接近我之前尝试建议的内容。

enum { BUFSZ = 50 };
enum { STRVSZ = 40 };
enum { STRVVSZ = 20 };
char buf[BUFSZ + 1];
char *strv[STRVSZ + 1];
char **strvv[STRVVSZ + 1];

int j; // indexes strv slices in strvv
int i; // indexes strings (char *s) in strv

j = 0; // j is index into strvv

while(!feof(infile)) {

i = 0; // i is index into strv
while(i < STRVSZ){
fgets(buf, BUFSZ, infile);
if (strcmp(buf,"END")==0) break; // end of a set

strv[i] = strdup(buf);
strv[i+1] = NULL;
i++;
} // i is count of strv

// copy strv into strvv
strvv[j] = calloc(i+1, sizeof *strvv[j]); // assuming i is the count of elements
memcpy(strvv[j], strv, (i+1) * sizeof *strvv[j]); // i+1 to copy the NULL pointer
j++; // index next element in strvv and a count of strvv

} // j is count of sets in strvv

感觉还是一团糟。

函数。它需要更小、定义明确的功能。这里的变量都是占位符,用于表示更有意义的内容。

关于C memcpy 未按预期运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16095994/

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