简体   繁体   English

C ++:如何获取指向二维动态数组的指针?

[英]C++: How to get pointer to 2 dimensional dynamic array?

I looked at this excellent answer but can't figure out how to apply it to this snipped: 我看了看这个出色的答案,但不知道如何将其应用于已被剪断的内容:

//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;

The assignment gives me 任务给了我

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

How can I obtain a pointer to 'locks'? 如何获得指向“锁”的指针?

错误消息实际上是免费提供解决方案的:

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

One can use the fact that this sort of thing has been officially declared to be ridiculously hard to get right for no apparent reason that the compiler cannot solve for you. 可以使用这样一种事实,即这种事情已经被正式声明为很难解决,而没有明显的原因使编译器无法为您解决。 If your compiler supports C++ 2011 that is. 如果您的编译器支持C ++ 2011。 Use: 采用:

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

Requires that you compile your code as C++ 2011 though. 但是要求您将代码编译为C ++ 2011。 ( -std=c++11 for GCC). (对于GCC为-std=c++11 )。

locks is just an array of pointers. locks只是一个指针数组。 So you could use a pointer pointer to point to it. 因此,您可以使用指针指针指向它。

std::recursive_mutex **locks_2 = locks;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM