首页 > 解决方案 > C程序输出奇怪的字符

问题描述

尝试在 C 中打印反向输入:

#include <stdio.h>

#define MAX_SIZE 100
/* Reverses input */
void reverse(char string[], char reversed[]);

int main() {
    char input[MAX_SIZE], output[MAX_SIZE + 1];
    char c;
    int index = 0;

    while ((c = getchar()) != '\n')
    {
        input[index] = c;
        ++index;
    }

    reverse(input, output);
    printf("%s\n", output);

}

void reverse(char string[], char reversed[]) {  
    int rev;
    rev = 0;

    for (int str = MAX_SIZE - 1; str >= 0; --str) {
        if (string[str] != '\0') {
            reversed[rev] = string[str];
            ++rev;
        }
    }
}

但有这个奇怪的结果:

输入:

美国广播公司

输出:

?:? ????:???:?cba?

输入和输出数组都包含\0,所以我猜有一些索引越界异常,但我无法找出确切的位置。谢谢你。

标签: creversec-stringsfunction-definition

解决方案


对于您不应该使用的原始字符串的长度,MAX_SIZE因为这是容器的总​​大小,而不是字符串的大小。

另一个问题是输入字符串不是以空值结尾的,因此无法知道它的长度,除非您跟踪从中读取的字符数stdin并将其作为参数传递。

修复这两个主要问题(以及其他一些小问题(评论))将使您的代码正常工作:

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

#define MAX_SIZE 100

void reverse(const char string[], char reversed[]);
int main()
{
    char input[MAX_SIZE], output[MAX_SIZE]; // no need for the extra character
    char c;
    int index = 0;

    while ((c = getchar()) != '\n' && index < MAX_SIZE - 1) // avoid buffer overflow
    {
        input[index] = c;
        ++index;
    }
    input[index] = '\0'; // null terminate the original string

    reverse(input, output);
    printf("%s\n", output);
}
void reverse(const char string[], char reversed[])
{
    int rev;
    rev = 0;

    // stop condition with the length of the string
    for (int str = strlen(string) - 1; str >= 0; --str)
    {
        reversed[rev] = string[str];
        ++rev;
    }
    reversed[rev] = '\0'; // null terminate the reversed string
}

推荐阅读