Когда я инициализирую свои массивы "temp" и "string", я ожидаю, что они смогут содержать строки длиной до 1000, потому что я инициализирую их с MAXLEN, который содержит значение 1000. Однако, когда я ввожу строку, которая большечем первый, который я ввел, я получаю сообщение:
Команда прервана
Я считаю, что ошибка в функции копирования, но я не понимаю, где и почему это происходит.
#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 меня испортила.Спасибо!