2013-07-03 69 views
0

我看着this excellent answer但無法弄清楚如何將其應用到該剪斷:C++:如何獲取指向2維動態數組的指針?

//this is in the .hpp file 
std::atomic<int> size = 10; 
std::recursive_mutex *locks[2]; 

//in some function of the class 
//it's important that the 2nd array dimension is dynamic 
the_lock[0] = new std::recursive_mutex[size]; 
the_lock[1] = new std::recursive_mutex[size]; 
std::recursive_mutex (*locks_2)[2][size] = &locks; 

分配給我

error: cannot convert ‘std::recursive_mutex* (*)[2]’ to ‘std::recursive_mutex (*) 
[2][(((sizetype)(((ssizetype)((**here be long type information, since I'm using 
templates a lot**, long unsigned int, std::less<long unsigned int>   
>::size.std::atomic<long unsigned 
int>::<anonymous>.std::__atomic_base<_IntTp>::operator 
std::__atomic_base<_IntTp>::__int_type<long unsigned int>()) + -1)) + 1)]’ in 
initialization 

我怎樣才能獲得一個指向「鎖定」?

+1

Arrrr ...請不要叫你的互斥鎖「鎖」。互斥體是一個互斥體,鎖是一個鎖。 –

+0

對不起。我試圖從一本書中實現Java風格的僞代碼,並且保留名字以避免混淆 – mort

+0

好的 - 我認爲這更多的是關於Java而不是關於你:-)(或者至少關於這本書。) –

回答

3

錯誤消息實際上是放棄了該解決方案免費:

std::recursive_mutex * (*locks_2)[2] = &locks; 
+0

這不行!'錯誤:無法將std :: recursive_mutex *(*)[2]'轉換爲'std :: recursive_mutex(*)[2]'初始化' – mort

+0

@mort:對不起,我忘記了一個'*'修正。 –

+0

好吧,現在它能正常工作。Thx! – mort

1

locks只是一個指針數組。所以你可以使用一個指針來指向它。

std::recursive_mutex **locks_2 = locks; 
+0

嚴格地說,這不是「指向'lock」的指針「。最好這是一個「指向鎖[0]的指針」。 –

+0

Works並且足夠滿足我的需求。 – mort

2

一個可以使用的事實,這樣的事情已經被正式宣佈爲可笑很難得到正確,沒有明顯原因是編譯器無法爲您解決。如果你的編譯器支持C++ 2011。使用:

auto my_ptr = &locks; // point to locks, let the compiler worry about types 

要求您將代碼編譯爲C++ 2011,儘管如此。 (GCC的-std=c++11)。

+0

沒問題,因爲我已經使用'-std = C++ 11'(儘管clang) – mort