我正在用 C 创建凯撒密码,但在显示编码消息时遇到问题。如果消息包含很少的字符,它会起作用,但一旦消息超过一定数量的字符,printf函数就会开始显示未知字符,我认为这些字符是垃圾字节。有什么想法吗?
代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *concat(const char *s1, const char *s2)
{
/*
Remember to free allocated memory
*/
char *result;
if((result = malloc(strlen(s1)+strlen(s2)+1)) != NULL)
{
result[0] = '\0';
strcat(result, s1);
strcat(result, s2);
}
return result;
}
void encode(const char *alpha, const char *message)
{
char result[(sizeof(message) / sizeof(char))];
int x, y, z;
memset(result, '\0', sizeof(result));
for(x = 0; x < strlen(message); x++)
{
for(y = 0; y < 25; y++)
{
if(alpha[y] == message[x])
{
z = (y + 3);
if(z > 25)
{
z = z % 25;
}
result[x] = alpha[z];
}
}
}
printf("%s\n", result);
//return result;
}
int main()
{
char message[200];
char *result;
char array[26] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };
printf("Input your message:");
scanf("%s", &message);
encode(array, message);
}
结果:
最佳答案
改变
char result[(sizeof(message) / sizeof(char))];
至
char result[strlen(message) + 1];
这会在缓冲区中为 terminating null-character 留出空间。 。 sizeof
也不能用来获取c字符串的长度,我们需要使用 strlen
为了这。您需要更新memset
也可以打电话。
sizeof
由编译器使用,因此在这种情况下,您将询问编译器“message
的大小是多少”,在本例中为 8(假设 64 位),因为指针是 8 个字节。
除此之外,您应该小心 scanf
,现在这样就很好,因为您读取了一行输入,但如果您尝试再读取一行,您可能会 run into trouble .
正如评论中提到的,for(x = 0; x < strlen(message); x++)
运行strlen
每次循环迭代一次,会给程序添加相当大的额外负载,随着 message
的长度呈指数增长。增加。
您的concat
函数未使用,不确定为什么包含它?
关于c - 打印字符数组时显示未知字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47177363/