当我初始化数组“temp”和“string”时,我希望它们能够保存长度最大为 1000 的字符串,因为我使用保存值 1000 的 MAXLEN 初始化它们。但是,当我输入一个更大的字符串时比我输入的第一个消息我收到消息:
命令终止
我相信错误出在复制函数中,但我不明白它发生在哪里或为什么发生。
#include <stdio.h>
#define MAXLEN 1000
int longestLine(char s[]);
void copy(char to[], char from[]);
// prints the longest line, and length of the longest line
int main()
{
int max;
char string[MAXLEN];
max = longestLine(string);
printf("max length is %d\n", max);
printf("%s\n", string);
return 0;
}
// returns the longest line in an input
int longestLine(char s[])
{
int max, cnt, c;
char temp[MAXLEN];
max = cnt = 0;
while((c = getchar()) != EOF)
{
if (c == '\n')
{
if (cnt > max)
{
max = cnt;
copy(s, temp);
}
cnt = -1; //if newline reset count
}
temp[cnt] = c;
cnt++;
}
return max;
}
// copys array contents from "from" to "to"
void copy(char to[], char from[])
{
int i;
for (i = 0; from[i] != '\0'; ++i)
{
to[i] = from[i];
} }
输入:
this is line one
this is line two which is longer
这是预期的输出:
max length is 32
this is line two which is longer
这是实际输出:
Command terminated
谢谢您的帮助!
编辑:
弄清楚了,cnt=-1 行把我搞乱了。谢谢!
最佳答案
有两件事:
您没有将“\0”指定为 temp 中的最后一个元素。因此,复制函数中的 for 循环可能会永远运行。在调用复制函数之前,将“\0”添加到 if block 中的最后一个条目。
即使您的输入末尾确实有“\0”,您也会在 if block 中将 cnt 重置为 -1。但是当它跳出 if 语句时,您的代码最终会为 tmp[-1] 分配一个值。在 if block 末尾使用 continue 语句。
关于c - 为什么当我向数组添加第七个字符时,我的代码会终止?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55481709/