我在初始化指针时遇到了一些问题。
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
。数组到指针的转换将数组转换为指向其第一个元素的指针。
关于c++ - 使用指针有困难,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21296699/