为什么我的代码在我的数组中添加第7个字符时会终止?

问题描述 投票:-2回答:1

当我初始化我的数组“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让我搞砸了。谢谢!

c arrays
1个回答
1
投票

两件事情:

  1. 您没有将'\ 0'指定为temp中的最后一个元素。因此,复制功能中的for循环可能永远运行。在调用复制功能之前,在if块中的最后一个条目中添加'\ 0'。
  2. 即使输入的末尾有'\ 0',也可以在if块中将cnt重置为-1。但是当它退出if语句时,你的代码最终会为tmp [-1]赋值。在if块的末尾使用continue语句。
© www.soinside.com 2019 - 2024. All rights reserved.