c - 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
,所以我猜有一些索引越界异常,但我无法找出确切的位置。谢谢你。
解决方案
对于您不应该使用的原始字符串的长度,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
}
推荐阅读
- excel - 如果项目同时在 A 列和 B 列中,则在 C 中打印
- reporting-services - SSRS - 有人可以向我解释 SSRS Stripline 属性吗?
- html - Html 悬停工具提示显示在其他图层下方。如何将其移至顶部?
- python - 导出带有自定义扩展名 Python 的文本文件
- jquery - jQuery上个月跳转到随机月份而不是上个月
- javascript - 通过带有参数的 emscripten 从 JS 调用 C 函数(指向缓冲区的指针)
- r - 在 R 中操作 Excel 工作表的数据/数据整理并更改布局
- swift - 计算两个特定字符之间的字符数
- scala - 具有速率和并发限制的 ExecutionContext
- wso2 - 如何将传入的查询参数传递给后端 WSO2 API 管理器