2016-12-02 196 views
-3

我想做一個函數,將無符號字符轉換爲無符號整型並將其存儲到數組中。但是,這最終會出現一個錯誤,說將無符號字符(數組)轉換爲無符號整數(數組)

將sprintf的參數1從不兼容的指針類型中傳遞。

int main(void) { 
    unsigned char key[16] = "1234567812345678"; 
    phex(key, 16); //store into an array here 
} 

uint64_t* phex(unsigned char* string, long len) 
{ 
    uint64_t hex[len]; 
    int count = 0; 

    for(int i = 0; i < len; ++i) { 
     count = i * 2; 
     sprintf(hex + count, "%.2x", string[i]); 
    } 

    for(int i = 0; i < 32; i++) 
     printf(hex[i]); 

    return hex; 
} 
+0

你想16個整數元素的數組,每個元素只保存一個數字嗎? – Rorschach

+3

'sprintf'將整數轉換爲字符表示,而不是其他方式 –

+0

A [*** *** sprintf'和'printf'的很好參考](http://en.cppreference.com/w/ c/io/fprintf)應該會有所幫助。 –

回答

1

正如評論已經說了,你必須在你的代碼的問題......所有sprintf功能 首先做的你想/希望它做的事情完全相反的事。接下來,在函數中創建一個局部變量,並返回指向它的指針。函數退出後,指針無效。第三個問題,我看到的是,你永遠不指定返回值什麼...就如何解決你的代碼

命題:

unsigned* phex(unsigned char* string, long len); 

int main(void) { 
    int i; 
    unsigned char key[16] = "1234567812345678"; 

    unsigned* ints = phex(key,16); //store into an array here 

    for(i = 0; i < 16; i++) 
     printf("%d ", ints[i]); 

    //never forget to deallocate memory 
    free(ints); 

    return 0; 
} 

unsigned* phex(unsigned char* string, long len) 
{ 
    int i; 
    //allocate memory for your array 
    unsigned* hex = (unsigned*)malloc(sizeof(unsigned) * len); 

    for(i = 0; i < len; ++i) { 
     //do char to int conversion on every element of char array 
     hex[i] = string[i] - '0'; 
    } 

    //return integer array 
    return hex; 
} 
+0

儘管'unsigned'與'unsigned int'相同,後者更清晰。你也不應該使用malloc http://stackoverflow.com/a/605858/4805077 – saeleko

+0

@LudaOtaku同意'unsigned int'。我甚至第一次寫它,然後修改它使其縮短。對我來說這似乎更加清楚。感謝您提供關於'malloc'的提示! – Rorschach

+0

我曾經單獨編寫'unsigned',無論如何它主要是一個品味問題,但是它讓閱讀代碼更加愉快,在它旁邊有一個小的'int'。並歡迎您使用malloc! 'void *'指針是C的一個非常有趣的方面。不管怎樣,你可能不想指向指針,總會有截斷地址的風險,這就意味着地平線上的麻煩。 – saeleko

相關問題