【发布时间】:2014-01-23 00:00:29
【问题描述】:
我在初始化指针时遇到了一些问题。
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?
【问题讨论】:
-
一个数组已经是一个指针。在调用 findMM 时从 &MM 中删除 &。
-
@TheSavage 这不是真的!
-
你能不能给我一个更详细的答案,原因只是让我感到困惑......
-
@TheSavage 数组不是指针。数组衰减指向数组第一个元素的指针。
-
你打算在 C 程序中也使用
findMM吗?如果不是,为什么要使用原始数组而不是 stl 容器?如果不将theG内的theG的大小(大小)作为参数传递,你怎么知道它的大小?
标签: c++ arrays pointers reference