我正在尝试实现一个简单的代码,它返回给定密码的相应 MD5:
#include <stdio.h>
//Returns the MD5 hash for a given password
char hash_password(char password){
FILE *fp;
char command [1024];
sprintf(command, "md5 <<< '%c'", password);
fp = popen(command, "r");
if (fp == NULL) {
printf("Failed to run command\n" );
}
char hashed[1024];
fgets(hashed , 1024 , fp);
pclose(fp);
return hashed;
}
int main(int argc, const char * argv[]) {
char hashed = hash_password("password");
printf("%s\n", hashed);
return 0;
}
我的问题如下:
- 我在
return hashed;
处收到警告:“从结果类型为 char 的函数返回 char[1024] 的整数转换指针不兼容” - 我在
char hashed = hash_password("password");
处收到警告:“将 char[9] 传递给 char 类型的参数时指向整数的指针不兼容” - 程序返回
\320
,这不是正确的哈希结果。
我两天的 C 经验表明该函数永远不会返回我需要的内容,因为 hashed
会随着函数的结束而消失,对吧?我怎样才能修复它?
最佳答案
- 你不能返回这样的临时数组。相反,让调用者传入一个指向数组的指针,然后写入其中。
- 与返回类型类似,如果您打算采用字符串,则参数不能为
char
。它应该是char*
或const char*
。
关于c - 如何处理不同大小的char变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32808580/