使用指针有困难

Having difficulty working with pointers

本文关键字:指针      更新时间:2023-10-16

我在初始化指针时遇到了一些问题。

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即可。数组到指针的转换将数组转换为指向其第一个元素的指针。

我知道这个问题已经得到了回答,但我相信我可以为提问者的理解做出贡献。

让我们从基础开始:

void main()
{
int a = 2; // a is an int
cout << a << endl; // print 2
int *b; // b is a pointer-to-int
b = &a; // store the address of a in b
cout << *b << endl;// print the value that b points to, which is 2
int my_array = new int[3]; // allocate an array with 3 integers
my_array[0] = 50; // store 50 in the first element of the array
my_array[1] = 51; // store 51 in the second element of the array
my_array[2] = 52; // store 52 in the third element of the array
cout << c[0] << endl; // print 50
some_function(my_array, 3); // explained below
}

现在让我们看看如何将数组传递到函数中。假设我们想要一个名为some_function的函数来接收数组。

void some_function(int *some_array, int size_of_the_array)
{
// use the array however you like here
}

该函数some_function接收指向int的指针(也称为"指向整数的指针")。数组的名称始终是其第一个元素的地址,因此,如果一个函数需要一个指向int的指针,并且您为其指定了int个数组的名称,那么您实际上是在为它提供数组中第一个元素的地址(这只是语法规则C++)。所以该函数现在具有数组中第一个元素的地址,它可以执行诸如*some_array之类的操作来访问数组中的第一个元素,但是如果它想要访问其他元素怎么办?它将 1 添加到已有的指针上,然后对其应用 * 运算符:*(some_array + 1)。假设一个int是 4 个字节,如果将 1 添加到指向 int 的指针中,则此添加的结果是一个新指针,该指针指向内存中领先 4 个字节的位置,因此数组的第 94 个元素中的值*(some_array + 93)some_array(数组元素按顺序存储在内存中)。对此的速记符号是some_array[93].所以如果你有int *some_array = new int[100];,那么some_array是一个指针,some_array[93]*(some_array + 93)相同,是数组中的第94个元素。

地址本身是不够的,您还需要知道数组中的条目数,这样您就不会尝试访问数组末尾以上的元素。在此示例中,假设some_function只是打印数组的内容,因此如果您不提供 3 作为函数的第二个参数,那么它将无法知道何时停止将 1 添加到它在第一个参数中收到的指针。但是请注意,通过以这种方式将数组传递给函数,您不会向函数传递数组的副本,而只是告诉它在内存中的位置可以找到其内容。