0

How do I access elements of a two dimensional array, using a pointer to that array?

std::recursive_mutex *(*A)[2];
std::recursive_mutex *B[2];
B[0] = new std::recursive_mutex[some_size];
B[1] = new std::recursive_mutex[some_size];
A = &B;

//accessing
//A[0][0]
//A[1]
//A[1][0]
//will not work (since the pointers do not point to the same locations as
//B[0][0]
//B[1]
//B[1][0]

Bonus question: is there a nicer way to initialize A? (without using std::vector)

4

1 回答 1

1

您的问题是您忘记取消引用 A,因为它是指向 B 的指针。

#include <mutex>

int main(int argc, char* argv[])
{
    size_t some_size = 5;
    std::recursive_mutex *(*A)[2];
    std::recursive_mutex *B[2];
    B[0] = new std::recursive_mutex[some_size];
    B[1] = new std::recursive_mutex[some_size];
    A = &B;

    auto& x = A[0][0];      // resolved to be std::recursive_mutex*&
    auto& y = (*A)[0][0];   // resolved to be std::recursive_mutex&

    return 0;
}

正如你所看到的,当你这样做时A[0][0],我们得到一个指向互斥体的指针,你想要的是互斥体本身,你可以通过取消引用 A 来获得它,就像这样:(*A)[0][0].

于 2013-07-04T16:20:26.480 回答