2017-03-24 25 views
-2

我有func(),它必須採用unsigned int參數。C++在64位平臺中傳遞char數組地址

存在用於空隙FUNC(無符號整數val)將原因,

我必須通過各種型(無符號字符,無符號短,無符號整型)至FUNC參數。

我必須將char數組傳遞給func(),我現在的解決方案就像下面的代碼。

編輯:有沒有簡單的方法在64位平臺上移植此代碼?

char test_str[128] = { 0 }; 
void func(unsigned int val) 
{ 
    memcpy(test_str, (char *)val, 128); //current my solution 
    printf("%s\n", test_str); 
} 

int main() 
{ 
    char str[128] = "hello world"; 
    func((unsigned int)(char *)&str); //current my solution 
    return 0; 
} 

注:使用intptr_t

+1

這是C++嗎?當我看到很多演員時,通常表示程序員做錯了 –

+0

函數必須有unsigned int,我應該將其更改爲模板嗎? – sailfish009

+0

爲什麼它應該有一個'unsigned int'?爲什麼在C++代碼中使用'printf'?你爲什麼把它標記爲C? –

回答

3

有很多的你的代碼的問題,但對我來說是一個至少編譯器首先抱怨的是:

error: cast from pointer to smaller type 'unsigned int' loses information │Offset: 4 byte: 0x7ffe4b93ddd4 contents:9 func((unsigned int)(char *)str);

我假設你」重新嘗試將char數組的文字地址隱藏到unsigned int參數中。然而,unsigned int只能保存4個字節(在我的平臺中),這不足以保存完整地址,因爲所有指針都需要8個字節(在我的平臺中)。你自己看。

#include <stdio.h> 

int main (int argc, char *argv[]) 
{ 
    char str[128] = "hello world"; 
    unsigned int *address = (unsigned int *)str; 

    printf("address: %p \t contains: %s \t pointer size: %lu \n", address, (char *)address, sizeof(char *)); 
    // address: 0x7ffcf9492540   contains: hello world   pointer size: 8 
    printf("Size of address in pointer: %lu \n", sizeof(long long *)); 
    // will print the same size as the past sizeof() operation 
    printf("Size of unsigned int variable: %lu \n", sizeof(unsigned int)); 
    // 4 bytes, not enough to fit in the necessary 8 bytes 

    return 0; 
} 
+0

感謝您的提示!順便說一句,在我的平臺所有4個字節。 – sailfish009

+0

https://msdn.microsoft.com/zh-cn/library/aa384267(VS.85).aspx找到一些幫助函數 – sailfish009