c - 为什么当我向数组添加第七个字符时,我的代码会终止?

标签 c arrays

当我初始化数组“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 行把我搞乱了。谢谢!

最佳答案

有两件事:

  1. 您没有将“\0”指定为 temp 中的最后一个元素。因此,复制函数中的 for 循环可能会永远运行。在调用复制函数之前,将“\0”添加到 if block 中的最后一个条目。

  2. 即使您的输入末尾确实有“\0”,您也会在 if block 中将 cnt 重置为 -1。但是当它跳出 if 语句时,您的代码最终会为 tmp[-1] 分配一个值。在 if block 末尾使用 continue 语句。

关于c - 为什么当我向数组添加第七个字符时,我的代码会终止?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55481709/

相关文章:

C - 如何在 for 循环中仅打印最大的数字?

php - 如何对多维数组进行urlencode?

javascript - 从一个巨大的数组中获取数据

C# 如果项目不在数组中

javascript - 计算数组一与数组二中字符串的出现次数

c - C++中复制字符串的函数选择,注重性能

c - 将 linenoise 库添加到 nixpkgs

javascript - 更改自定义数组中键的值

c - c 中的全局计数器未按预期工作

c - Fork 函数不返回 0 值?