在单个 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/