开发者

C++ passing/accessing matrix by pointers [duplicate]

开发者 https://www.devze.com 2023-02-20 22:57 出处:网络
This question already has answers here: Closed 11 years ago. P开发者_如何学Pythonossible Duplicate:
This question already has answers here: Closed 11 years ago.

P开发者_如何学Pythonossible Duplicate:

2D arrays with C++

Hi, I'm trying to copy a pointer to a matrix that i'm passing in to a function in C++. here's what my code is trying to express

#include <iostream>
using namespace std;

void func( char** p  )
{
    char** copy = p;
    cout << **copy;
}

int main()
{   
    char x[5][5];
    x[0][0] = 'H';
    func( (char**) &x);
    return 0;
}

However, this gives me a Seg Fault. Would someone please explain (preferrably in some detail) what underlying mechanism i'm missing out on? (and the fix for it)

Thanks much in advance :)


A pointer to an array of 5 arrays of 5 char (char x[5][5]) has the type "pointer to array of 5 arrays of 5 chars", that is char(*p)[5][5]. The type char** has nothing to do with this.

#include <iostream>
using namespace std;

void func( char (*p)[5][5]  )
{
    char (*copy)[5][5] = p;
    cout << (*copy)[0][0];
}

int main()
{
    char x[5][5];
    x[0][0] = 'H';
    func(&x);
    return 0;
}

Of course there are many other ways to pass a 2D array by reference or pointer, as already mentioned in comments. The most in-detail reference is probably StackOverflow's own C++ FAQ, How do I use arrays in C++?


char** is a pointer to a pointer (or an array of pointers). &x is not one of those - it's a pointer to a two-dimensional array of chars, which can be implicitly converted to a pointer to a single char (char *). The compiler probably gave you an error, at which point you put in the cast, but the compiler was trying to tell you something important.


Try this instead of using a char**:

#include <iostream>
using namespace std;

void func( char* &p  )
{
    char* copy = p;
    cout << copy[0];
}

int main()
{   
    char x[5][5];
    x[0][0] = 'H';
    func(&x[0]);
    return 0;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消