【发布时间】:2021-01-05 05:38:41
【问题描述】:
在没有库函数的情况下,我无法在 C 中连接字符串。 我尝试了以下方法:
#include <stdio.h>
struct word {
char *str;
int wordSize;
};
void concat(struct word words[], int arraySize, int maxSize) { // word array, its size, and max size given
char result[maxSize];
int resultSize = 0;
struct word tmp;
for (int i = 0; i < arraySize; i++) {
tmp = words[i];
for (int j = 0; j < words[i].wordSize; j++, resultSize++) {
result[resultSize + j] = tmp.str[j];
}
}
puts(result);
}
例如,如果结构数组words 包含[{"he", 2}, {"ll", 2}, {"o", 1}],则result 应该是hello。但是,此代码打印h�l�o,其中第二个和第四个字母是问号。谁能帮我调试一下?
【问题讨论】:
-
result[resultSize + j] = tmp.str[j];是错误的,您在每次迭代中递增j和resultSize,因此您将跳过result中的每个第二个索引。 -
@mch 我明白了。感谢那。这解决了问题。
-
@mmmdwldmm 除我之外的所有答案都是错误的,并且提供的函数可以调用未定义的行为。
标签: c struct concat c-strings function-definition