C++通过指针传递/访问矩阵
可能的重复:
C++ 的二维数组
嗨,我正在尝试将指针复制到我的矩阵m 传递给 C++ 中的函数。这就是我的代码试图表达的内容
#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;
}
但是,这给了我一个段错误。有人可以解释一下(最好是详细一些)我错过了什么底层机制吗? (以及修复它)
提前非常感谢:)
Possible 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 :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
指向 5 个 5 个字符数组的数组的指针 (
char x[5][5]
) 的类型为“指向 5 个 5 个字符数组的数组的指针”,即char( *p)[5][5]
。类型char**
与此无关。当然,还有许多其他方法可以通过引用或指针传递 2D 数组,正如注释中已经提到的。最详细的参考可能是 StackOverflow 自己的 C++ FAQ,How我在 C++ 中使用数组吗?
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 ischar(*p)[5][5]
. The typechar**
has nothing to do with this.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**
是一个指向指针(或指针数组)的指针。&x
不是其中之一 - 它是一个指向二维字符数组的指针,可以隐式转换为指向单个字符的指针 (char *
)。编译器可能给你一个错误,此时你进行了强制转换,但编译器试图告诉你一些重要的事情。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.尝试这个而不是使用 char**:
Try this instead of using a char**: