在 K&R 中,我们介绍了 char 数组来表示字符串。
数组通过引用传递。据我了解,我们可以指向数组中的第一个元素(指针?)。使用 char 数组 input
而不真正定义它的值意味着它在数组内设置垃圾数据。 (老实说,我不太确定什么是垃圾数据,也许是空值?)。
无论如何,最初将空字符数组传递给函数 getLength
,并设置字符数组输入。在我的代码中,我显示了 len
和 char 数组 input
。
在下一个输入中,我再次调用 getLength
,并传递相同的字符数组 input
。我像以前一样设置值并返回长度。
如何删除旧输入?我引用的不是与先前存储先前输入的完全相同的数组吗?在我的代码下方,我将展示一个示例。
#include <stdio.h>
#define MAXLINE 1000 /* For allocating storage size for char array */
int getLength(char s[]); /* set char array and return length */
int main(void) {
int len;
char input[MAXLINE];
while ((len = getLength(input)) > 0) {
printf("len = %d\n", len);
printf("string = %s", input);
}
}
int getLength(char s[]) {
int i, c;
for (i = 0; i < MAXLINE - 1 && (c = getchar()) != EOF && c != '\n'; ++i) {
s[i] = c;
}
if (c == '\n') {
s[i++] = '\n';
}
s[i] = '\0';
return i; /* return length including newline */
}
例子:
Input: "Hello my name is Philip"
Output: "len = 24"
"string = Hello my name is Philip"
Input: "Hi"
Output: "len = 3"
"string = Hi"
当我输入“Hi”时,我不是在使用之前存储了“Hello my name is Philip”的数组吗?所以我不希望数组看起来像:
['H', 'i', '\n', '\0', 'o', ' ', 'm', 'y', ' ', 'n', 'a', 'm', 'e', ' ', 'i', 's', ' ', 'P', 'h', 'i', 'l', 'i', 'p', '\n', '\0', etc...]
编辑:
澄清一下,我理解 printf("%s", input)
是如何打印正确的字符串的。我也明白 getLength
每次都会返回正确的长度。
我只是对数组 input
中保存的字符感到困惑。如果我们在内存中引用同一个数组,如何处理旧字符?
最佳答案
How is the old input erased? Aren't I referencing the exact same array that previously stored the previous input?
旧输入未删除。在循环的每次迭代中,您只是覆盖相同的数组 input
并由 以零终止 (
在每次迭代中。s[i] = '\0';
) getLength()
由于您在下一次迭代之前 打印字符串,因此可以重用相同的数组(并覆盖它)。所以,真的没有必要“保存”任何东西。
关于c - K&R 如何重置字符数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39236515/