c - 简单的单字符数组加密需要一个人为的长数组才能工作吗?

标签 c arrays encryption

在单个 char 数组上运行简单的加密。当数组大小小于或等于 1 时,它似乎不起作用,即使只有一个字符在变化。

以下内容有效,因为 yesCrypto[10] 设置为 10(或 > 1)。

char noCrypto[] = "H";    //sets an array to hold unencrypted H
char yesCrypto[10];        //sets array to hold encrypted H

yesCrypto[0]=noCrypto[0]+1;              
//takes 'H' from noCrypto and turns it into an 'I' and moves it into yesCrypto.

printf("Encrypted string is '%s'\n", yesCrypto);        
//prints Encrypted version of 'H', 'I'

以下不起作用,因为 yesCrypto[0] 设置为 0,当设置为 1 时也不起作用。

char noCrypto[] = "H";    //sets an array to hold unencrypted H
char yesCrypto[1];        //sets array to hold encrypted H

yesCrypto[0]=noCrypto[0]+1;              
//takes 'H' from noCrypto and turns it into an 'I' and moves it into yesCrypto.

printf("Encrypted string is '%s'\n", yesCrypto);        
//prints 'IH'

附带问题:为什么它在可能不工作时打印 IH。

最佳答案

代码正在尝试使用 "%s" 打印不是 字符串 的字符数组。

yesCrypto[] 不一定空字符终止。

char yesCrypto[10];
yesCrypto[0] = noCrypto[0]+1; 
printf("Encrypted string is '%s'\n", yesCrypto); // bad

相反,限制打印或附加一个空字符

// 1 is the maximum number of characters to print
printf("Encrypted string is '%.*s'\n", 1, yesCrypto);
// or 
yesCrypto[1] = '\0'; 
printf("Encrypted string is '%s'\n", yesCrypto);

OP 的第二个代码很糟糕,因为长度为 0 的对象数组缺乏定义的行为。

// bad
char yesCrypto[0]; 

OP 的编辑帖子使用 char yesCrypto[1];。在那种情况下使用

yesCrypto[0] = noCrypto[0]+1; 
printf("Encrypted string is '%.*s'\n", 1, yesCrypto);
// or 
printf("Encrypted character is '%c'\n", yesCrypto[0]);

从根本上说,将加密数据打印为字符串是一个问题,因为加密字符数组可能在很多地方包含一个空字符和一个字符串 需要一个空字符并以第一个字符结尾。

关于c - 简单的单字符数组加密需要一个人为的长数组才能工作吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43920873/

相关文章:

阿拉伯文C文件操作字体

c - 带参数的通用多行宏

c - 我在哪里定义 C 中的 const 数组?

arrays - 如何遍历二维数组的特定行?

c++ - 如何强制long为4字节

在 C 中强制转换然后取消引用指针

c - 如何在 C 编程中执行 Shell 脚本,接收反馈和处理器 ID,并关闭进程

asp.net - RSAProtectedConfigurationProvider 在 web.config 加密中使用了哪些算法?

sql-server - SQL Server "with encryption"语句的有用性

php - 正确使用 php openssl_encrypt 的方法