【发布时间】:2017-08-10 14:02:16
【问题描述】:
我正在尝试创建一个非常简单的加密函数,它接受一个字符数组并返回另一个字符数组,其值加一。
准确解释:
输入是用户插入的一行文本。
我希望数组line 例如“abcdef”变成“bcdefg”。
真正发生的是我无法增加每个角色的价值,我不知道该怎么做。
我没有从编译器得到任何错误,只是结果错误,我认为问题与strcat有关,但我无法想象如何解决。
由于我是一名 C 学生,因此在回答中我想要一些东西来修复我的程序,如果可能的话,而不是一个全新的程序。
#include <stdio.h>
#include <string.h>
char line[20];
char duplicated[20];
char hashed[];
/********************************************************
* hashf -- Simple hash function that takes a character *
* array and returns that takes a character *
* array and returns another character array *
* with its value increased by one. *
* *
* Parameters -- string duplicated from the text *
* inserted by the user *
* *
* Returns -- the hashed array (supposed to...) *
********************************************************/
char hashf(char duplicated[]) {
hashed[0] = '\0';
for (int i = 0; duplicated[i] != '\0' ; ++i) {
duplicated[i] += 1;
strcat(hashed, duplicated[i]);
}
return (hashed);
}
int main() {
printf("Put a text to hash: ");
fgets(line, sizeof(line), stdin);
strcpy(duplicated, line); // strcpy(string1, string2) -- copy string 2 into string 1
/* This two line are used to remove the '\n' character from the end of the array */
duplicated[strlen(duplicated)-1] = '\0';
line[strlen(line)-1] = '\0';
printf("The text %s become %s", line, hashf(duplicated));
}
【问题讨论】:
-
您应该启用并注意编译器警告。
-
"我认为问题与strcat有关,[...]" 欢迎来到stackoverflow。 stackoverflow 是这样工作的:你展示你的代码,你准确地解释你给它的输入,你准确地解释发生了什么,你准确地解释你期望发生什么。如果它爆炸了,你准确地解释你得到了什么错误,在哪一行。
-
如果在调用代码中忽略它,为什么要返回一个指针?
-
@MikeNakis 对不起,你完全正确,我不是故意要问一个乱七八糟的问题。
-
看起来你正在使用 gcc。请永远不要在没有这些参数的情况下运行 gcc:
-Wall -Wextra -Wpedantic -Werror -std=c99(或-std=c11)。将为您(和我们)节省大量时间。
标签: c string function hash char