首页 > 解决方案 > 我在哪里寻址我不拥有的内存?(字符数组)

问题描述

该程序的目的是将每个单词打印在自己的行上,并带有行数和单词数。它编译得很好,没有警告,但似乎我正在处理我不拥有的内存,因为我得到了我Abort trap:6,但我不知道在哪里以及为什么。我已经查找了具有相同错误的其他问题,但那里的答案没有帮助。

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
    int word = 1, line = 1, a = 0;
    char str[1], w[70];
    strcpy(w, " ");
    while (a != EOF)
    {
        a = getchar();
        if ((a != EOF) && (a == ' ' || a == '\t' || a == '\n'))
        {
            ++word;
            if (a == '\n')
                ++line;
        }
        if (a != EOF && a != ' ' && a != '\t' && a != '\n')
            sprintf(str, "%d", a);
        strcat(w, str);
        if (a == ' ' || a == '\t' || a == '\n' || a == EOF)
        {
            printf("\n %d.%d%s", line, word, w);
            strcpy(w, " ");
        }
    }
    return 0;
}

标签: carrayschar

解决方案


char str[1]不能容纳任何长度超过 0 的字符串,因为 C 字符串的定义是由一个空字符终止的字符数组。因此,您的str数组必须为 2 个字节才能同时包含至少 1 个char和 1 个空字符 ( '\0')。这很可能是困扰您的原因。

我修改了你的代码,让它按照你想要的方式工作,但你必须微调你发现不需要的异常。阅读我通过以下调整留下的笔记:

char str[1] -> char str[2]

大小必须至少为 2 以容纳 char 和空终止字符 ( \0)。

sprintf(str, "%d", a) -> sprintf(str, "%c", a)

您将 char 格式化为int,因此当您稍后连接字符串时得到数字而不是文本的原因。

最后,由于这个原因,您的最后一个字符被打印了两次:

if (a != EOF && a != ' ' && a != '\t' && a != '\n')
    sprintf(str, "%c", a);
strcat(w, str);

strcat(w, str);不在EOF检查范围内,因此无论如何它都会连接最后一个字符。

输出:

在此处输入图像描述

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main() {
    int word = 1, line = 1, a = 0;
    char str[2], w[70];
    strcpy(w, " ");
    while (a != EOF) {
        a = getchar();
        if ((a != EOF) && (a == ' ' || a == '\t' || a == '\n')) {
            ++word;
            if (a == '\n')
                ++line;
        }
        if (a != EOF && a != ' ' && a != '\t' && a != '\n') {
            sprintf(str, "%c", a);
            strcat(w, str);
        }
        if (a == ' ' || a == '\t' || a == '\n' || a == EOF) {
            printf("%d.%d%s\n ", line, word, w);
            strcpy(w, " ");
        }
    }
    return 0;
}

推荐阅读