在初始化指针时,我遇到了一些问题。
void findMM (int *PMM, int *theG)
{
// code I haven't written yet. It will essentially take two variables from //theG and store it in MM
}
int main()
{
int size;
int MM [2] = {1000, 0};
int *theG = NULL;
cout << "\nPlease insert size of array:" << endl;
cin >> size;
theG = new int [size];
findMM(&MM, &theG); //Get error with &MM
delete [] theG;
return 0;
}
编译器说类型的int (*)[2]
参数与类型的参数不兼容。int **
很显然,我对代码的问题特别是我对数组MM的引用(引用?)有问题。或者,也许还有其他明显的错误我想念吗?
编辑尝试2
void findMM (int *PMM, int *theG)
{
PMM [1] = 5;
theG [0] = 7;
}
int main()
{
int size;
int MM [2] = {1000, 0};
int *theG = NULL;
cout << "\nPlease insert size of array:" << endl;
cin >> size;
theG = new int [size];
findMM(MM, theG);
cout << MM [1] << endl << theG[0];
delete [] theG;
return 0;
}
输出将是5和7正确吗?
因为MM
是数组,所以&MM
是指向数组的指针(这int (*)[2]
是您在错误中看到的类型)。相反,您似乎想要将指针传递给数组的第一个元素。有两种方法可以做到这一点。首先,您可以显式获取第一个元素,然后获取其地址:&MM[0]
。其次,您可以依靠数组到指针的转换为您完成此操作,然后通过即可MM
。数组到指针的转换将数组转换为指向其第一个元素的指针。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句