我有一个这样的二维数组:
void getC(int **p)
{
*p = &c[0][0];
}
int c[10][10];
int *a;
getC(a);
a[0][0];
it says error: no match for 'operator[]' in `a[0][0];` what is the problem and how to fix it?
您正在使用 C++ 编译器编译 C 程序。小心!
您需要将定义放在函数c上方getC(或提供前向声明)。
您在函数之外有语句,这在 C 中是不允许的。int *a用int main(void) { ... }
您需要 a&才能使您的getC()通话合法-您正在传递 a int *,但它期望int **:
getC(&a);
该语句a[0][0]没有任何效果,并且无论如何都是错误的,因为a它只是一个int *; 你不能取消引用它两次。
您可能应该得到一本初学者的 C 书并开始阅读它。
本质上,您只需返回 2dim 数组的第一个元素的地址,就可以将数组/指针从int (*)[10](指向 10 int 数组的指针)降级为 simple 。int pointer虽然这在技术上是正确的(2dim 数组的一个元素的地址当然是 int*),但有关数组中 int 的结构/布局的信息会丢失,因此生成的 a-ptr 现在什么都没有关于 int 是 [10][10] 结构的一部分的事实。
在您的情况下,获取数组元素的唯一方法是将您的方式乘以 int 数组,基于您自己的知识,即在地址 a 有 100 个以 10x10 组织的整数:
int *a;
getC(&a);
...= a[10*x + y]; // equivalent of c[x][y];
.
但是,本质上,正确的方法(完全保留类型)将是
int c[10][10];
void getC(int (**p)[10]) // pointer to pointer to array of 10 ints
{
*p = c; // c itself can seamlessly change into a pointer to one sub-element
// (i.e. pointer to array of 10)
}
int main()
{
int (*a)[10]; // pointer to array(s) of 10 ints
int q;
getC(&a);
q= a[9][9];
...
}
再次增加一个维度级别(可能是最直观的解决方案):
但是,本质上,正确的方法(完全保留类型)将是
int c[10][10];
void getC(int (**p)[10][10]) // pointer to pointer to array of 10x10 ints
{
*p = &c; // &c can seamlessly change into a pointer to 10x10 ints
}
int main()
{
int (*a)[10][10]; // pointer to array(s) of 10x10 ints
int q;
getC(&a); // pass adress of pointer to 10x10 ints
q= (*a)[9][9]; // need *a in brackets to derference the pointer (operator precedence)
...
}