以下截取的代码是对我当前正在处理的代码的简化。它旨在构造一个输出字符串,通过字符串的连接构造。
#define _GNU_SOURCE
#include <argp.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
#include <float.h>
#include <math.h>
#include <string.h>
int main(void) {
char *english[] = {"zero", "one", "two", "three", "four", "five",
"six", "seven", "eight", "nine"};
char *l_english = malloc(5*sizeof(char)*10+10+1);
char *ptr_eng = l_english;
for(int i = 0; i<10; i++){
ptr_eng = mempcpy(ptr_eng,english[i],strlen(english[i]));
printf("Iteration %d\n",i);
}
free(l_english);
return 0;
}
我在 Gentoo Linux 下用 gcc 4.8.3 编译。当我运行上面的程序时,它不会停止但会消耗 100% 的 CPU 内核。用 gdb 查看,结果是 mempcpy
进入了无限递归。
现在谈谈我已经尝试过的事情:
- 展开 for 循环。如果我简单地写出指令而不是使用 for 循环,这将非常有效。
- 为 mempcpy 设置一个常量大小来复制。再说一次,没有无休止的递归。
- 使用
memcpy
并且不更改循环内的指针“ptr_eng”:同样,没有无穷无尽的递归。 - 关于 3.,使用
memcpy
并设置eng_ptr = eng_ptr+strlen(english[i])
。又一次,无休止的递归发生了。
可悲的是,当我用谷歌搜索 memcpy
和 for-loops 时,我只找到有关性能的讨论。我是 C 方面的新手,如果您能提供任何指导,我将不胜感激。
编辑
这里是相关 gdb 输出的链接 http://pastebin.com/nBZhqnsw ;这一直持续到发生段错误为止。
编辑 2
澄清一下:上面的代码只是我目前正在开发的一个程序的简化示例。 malloc
调用中的大小公式实际上只是对一些用于计算实际程序中实际所需内存量的变量的一次性替换。这个例子唯一重要的是它有足够的内存来保存 english
变量中的十个单词。
l_english 的预期结果是指向包含“zeroonetwothreefourfivesixseveneightnine”的内存块开头的指针。就像我说的,这只是为了 Stack Overflow 的简化。
最佳答案
我不知道为什么它不起作用,所以我只建议您保持程序简单,一切都会很好:
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
int main(void) {
const char* english[] =
{
"zero",
"one",
"two",
"three",
"four",
"five",
"six",
"seven",
"eight",
"nine"
};
char *l_english = malloc(5*sizeof(char)*10+1); // 5 chars times 10 plus nul
char *ptr_eng = l_english;
for(size_t i=0; i<10; i++)
{
const char* ptr_ch = english[i];
while(*ptr_ch != '\0')
{
*ptr_eng = *ptr_ch;
ptr_eng++;
ptr_ch++;
}
printf("Iteration %d\n",i);
}
*ptr_eng = '\0';
puts(l_english);
free(l_english);
return 0;
}
输出:
Iteration 0
Iteration 1
Iteration 2
Iteration 3
Iteration 4
Iteration 5
Iteration 6
Iteration 7
Iteration 8
Iteration 9
zeroonetwothreefourfivesixseveneightnine
另外,上面的while循环比memcpy + strlen更高效。
关于c - 使用 mempcpy 在 for 循环中串行构造字符串会导致无限递归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25262830/