2011-11-21 70 views
6

我想爲一個臨時變量分配一個靜態分配的多維數組。請看下面的例子:如何將多維數組分配給臨時變量?

void foo(int b[3][2]) 
{ 
    b[1][1] = 1; // no segmentation fault 
} 

int main() 
{ 
    int a[3][2] = {{1, 2}, {11, 12}, {21, 22}}; 

    foo(a); 

    int** c; 
    c = (int**)&a; 
    c[1][1] = 1; // segmentation fault on execution 

    int* d[3]; 
    d[0] = (int*)&(a[0]); 
    d[1] = (int*)&(a[1]); 
    d[2] = (int*)&(a[2]); 
    d[1][1] = 1; // no segmentation fault 

    return 0; 
} 

基本上我想要做的編譯器與參數的foo()b什麼。但是我能想到的唯一工作解決方案是d。有沒有更簡單的方法?

+0

奇怪的是,有多少人認爲2D數組直接轉換爲指向指針的指針。 – tenfour

回答

11

cdeclman page)是你的朋友:

cdecl> explain int b[3][2] 
declare b as array 3 of array 2 of int 
cdecl> declare b as pointer to array 2 of int 
int (*b)[2] 

所以,試試這個:

void foo(int b[3][2]) 
{ 
    b[1][1] = 1; // no segmentation fault 
} 

int main() 
{ 
    int a[3][2] = {{1, 2}, {11, 12}, {21, 22}}; 

    foo(a); 

    int (*b)[2] = a; 

    b[1][1] = 1; 

    return 0; 
} 
+0

呵呵 - 這是新的。哪裏/什麼是cdecl? – sehe

+0

OMG _cdecl_:D:D:D我從來沒有見過這樣的:D在線版本:@sehe - http://cdecl.org/ –

+1

+1,感謝cdecl ;-) –

9

int[3][2]int**是不兼容的類型。你不能投一個到另一個。

試試這個:

int (*c)[2]; 
c = a; //no need to cast 
c[1][1] = 1; //ok 

或者你可以做到這一點(聲明以及初始化):規則的

int (*c)[2] = a; //no need to cast 
c[1][1] = 1; //ok 

大拇指:

  • 不要在C++中使用C風格的轉換。使用C++風格的轉換。假如你用C++ - 風格的演員,編譯器會告訴你這個問題變得之前(ideone)(不需要運行代碼,看問題):

    prog.cpp:5: error: invalid static_cast from type ‘int (*)[3][2]’ to type ‘int**’ 
    

    但C樣式轉換編譯它罰款(正如你已經知道的那樣。

  • 而且,無論何時使用強制轉換,即使是C++風格強制轉換,如果程序無法正常工作,您的第一個疑問應該是強制轉換。

+1

你有一個錯字:) –

+1

@KirilKirov:固定。謝謝。 – Nawaz

2

如果您使用的是支持C++ 11標準的足夠的零件相當現代的編譯器,你可以使用auto

int a[3][2] = ...; 
auto &b = a; 
b[1][1] = 1; // a[1][1] will be set 

當然,無論ab必須定義在相同的範圍內工作。你不能在例如功能的auto參數(這就是模板是。)

5

正如你現在可能知道,從其他的答案中,a的類型不是實際上相當於int** - 它僅僅指剛衰減到那個(當返回/通過值)。

int (*b)[2] = a; // would solve that 

有一個以上的C++方式:

typedef std::array<std::array<int, 2>, 3> M23; 

void foo(M23& b) 
{ 
    b[1][1] = 1; 
} 

int main() 
{ 
    M23 a = {{1, 2}, {11, 12}, {21, 22}}; 

    foo(a); 

    M23 d = a; 
    d[1][1] = 1; 
} 
+1

+1大家都喜歡'std :: array' :-) –

+1

@sehe:這很好,但你也應該回答這個問題,並用OP的代碼解釋問題。一旦你解釋了,你可以建議更好的替代解決方案。 – Nawaz

1

不顯式轉換,所以儘量寫

c = &a; 

然後GCC編譯器(使用gcc -Wall -g bidim.c -o bidim編譯)給你正確的警告:

bidim.c:13:7: warning: assignment from incompatible pointer type [enabled by default] 

然後你應該認識到2D矩陣不是作爲指向1D數組的指針數組來實現的。

0

是進入我的心是用一個typedef和參考樣

typedef int thing_t[3][2]; 
thing_t& e = a; 
e[1][1] = 1; 

隨着指針

int (*f)[2] = a; 
f[1][1] = 1; 

另一種可能性是將其封裝在struct的第一件事情。