2010-08-19 82 views
2

所以,我有一些指針問題。 我正在寫一個函數,它將內存地址存儲在[]中。 這些內存地址指向b []中的實際數據值。 我無法從b獲取內存地址以存儲在。問題獲取和存儲陣列中的內存地址

// Assume these are initialized to 0 outside of this snippet 
char a[100]; 
char b[100]; 
b[0] = 42; // Some value for us to use 

int* a_ptr = (int*)&a[0]; // Store the address of a[0] in a_ptr 
int* b_ptr = (int*)&b[0]; // Store the address of b[0] in b_ptr 

*a_ptr = (int)&b_ptr; // PROBLEM LINE. The first four bytes of a[] 
         // should contain the memory address of b[0]. 
         // However, it does not. Here are the debugger values: 
         // a_ptr = 0x00429148 
         // b_ptr = 0x00429151 
         // a[0] SHOULD be 0x00429151, but it is instead 0x0012fe4c. 

是否有一些技巧我需要做的,以獲得0x00429151存儲在[0..3]?

+0

爲什麼標記C++? 「 – tristan 2010-08-19 04:39:30

+0

」應該包含b [0]的內存地址嗎?如果你想讓它們包含「b [0]」的內存地址,你爲什麼強制使用'b_ptr'的地址而不是'b [0]'的地址? – AnT 2010-08-19 04:59:44

回答

0

沒關係...顯然太晚了。

要解決,改變

*a_ptr = (int)&b_ptr; 

*a_ptr = (int)b_ptr; 
+0

你爲什麼要通過'int'去?爲什麼'int *'當實際對象是'char'時? 'char ** a_ptr =(char **)&a[0]; * a_ptr = &b[0];'會更有意義。 – caf 2010-08-19 04:45:28

+0

原因是我需要b [0]的內存地址,而不是數值。指針不適合char內部,因爲它通常是4個字節,char是1. Int是4個字節。 – CrypticPrime 2010-08-19 11:06:22

4
*a_ptr = (int) b_ptr; 

每評論

+0

'a_ptr'已經是'int *'了。不需要施放它。 '* a_ptr =(int)b_ptr'。 – AnT 2010-08-19 04:58:06

+0

是的。我沒有看到它的權利。 – tristan 2010-08-19 05:19:44

0

哎呀更新 - 什麼亂七八糟的。如果a和b是char數組,那麼你不想爲它們創建int ...... int是一個比char更大的內存區域,當你讀到的時候你會在char的旁邊找到其他值並最終得到一個有效的隨機值。如果嘗試存儲到int,則會打破char的值(可能具有意想不到的值),同時在其周圍打開幾個值。

在學習C++時,不要使用C風格的強制轉換(例如「(int *)」)是一個非常好的主意。如果你使用static_cast,編譯器會告訴你什麼時候你犯了一個大錯誤。

所以,你想要的是:

 
    char* p_a = &a[0]; 
    char* p_b = &b[0]; 
    *p_a = *p_b; // copy 
+0

「你會在char旁邊找到其他的值」。這正是我想要的。這些實際上是存儲任意數量類型的字節數組 - 不是單個字符。把b [0]看作緩衝區。如果我想在b [0]處存儲一個int,那麼它將使用b [0] -b [3]。這是我想要的。這就是爲什麼我需要b [0]的地址。我可以返回存儲在[0]中的b [0]的地址,所以調用函數(知道類型)知道要讀/寫多少字節到b []; – CrypticPrime 2010-08-19 11:10:02

0

雖然有更好的方法來做到這一點,這可能是最接近你的方法

int main(){ 
    char *a[100];  // not char but char * 
    char b[100]; 
    b[0] = 42;   // Some value for us to use 

    char** a_ptr = (char **)&a[0]; // Store the address of a[0] in a_ptr 
    char* b_ptr = (char*)&b[0];  // Store the address of b[0] in b_ptr 

    *a_ptr = b_ptr; 
    } 
+0

不幸的是,a和be必須保持原樣。 – CrypticPrime 2010-08-19 11:11:58