简体   繁体   中英

How to access elements of a pointer to 2 dimensional array correctly?

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)

Your problem is you forgot to dereference A as it is a pointer to 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;
}

As you can see, when you do A[0][0] as you did we get a pointer to a mutex, what you want is the mutex itself, you get that by dereferencing A which is done like so: (*A)[0][0] .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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