我有一个程序来通过用户输入,发送该用户输入作为一个参数传递给函数,这使得计算,则该字符数组返回到主()函数将要输出那里。返回char数组失败,且不printf()的
的return (char *)&buf;
运行一个printf()
语句时工作正常。 然而,当没有printf()
,回报似乎并没有工作,因为main()
功能无法输出返回值。
下面的代码:
#include <stdio.h>
#include <string.h>
#include <openssl/sha.h>
using namespace std;
char* hash_function(char* input_string)
{
int i = 0;
unsigned char temp[SHA_DIGEST_LENGTH]; //where we will store the SHA digest. length = 20
char buf[SHA_DIGEST_LENGTH*2];
memset(temp, 0x0, SHA_DIGEST_LENGTH); //array of size 20 to store SHA1 digest
memset(buf, 0x0, SHA_DIGEST_LENGTH*2); //array of size 2*20 to store hex result?
SHA1((unsigned char *)input_string, strlen(input_string), temp);
for(i=0; i<SHA_DIGEST_LENGTH; i++){
sprintf((char*)&(buf[i*2]), "%02x", temp[i]);
//element in temp[i] formatted with %02x and stored in buf[i*2]
}
//printf("In FUNCTION: %s\n", buf); //*************************************
return (char *)&buf;
}
int main(int argc, char * argv[])
{
if(argc != 2)
{
printf("Usage: %s <string>\n", argv[0]);
return -1;
}
char *hash = hash_function(argv[1]);
printf("Plaintext:\t%s\nSHA-1:\t\t%s\n\n", argv[1], hash);
//FILE *file = fopen("temp_file.txt", "a+"); //open file to write to
//fprintf(file, "Plaintext: %s\nSHA-1: %s\n\n", argv[1], buf);
return 0;
}
我已经用星号标记的线是print()
线我指的是。
为了编译,使用g++ [file_name] -lcrypto -o [output]
您可能需要下载的OpenSSL/sha.h包。
'使用命名空间std;'是不是C. –
'buf'成为功能之外无效。 – BLUEPIXY
请不要期望评论者“下载openssl/sha.h包”。 –