我有一個程序來通過用戶輸入,發送該用戶輸入作爲一個參數傳遞給函數,這使得計算,則該字符數組返回到主()函數將要輸出那裏。返回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包」。 –