使用指针有困难
Having difficulty working with pointers
我在初始化指针时遇到了一些问题。
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 添加到它在第一个参数中收到的指针。但是请注意,通过以这种方式将数组传递给函数,您不会向函数传递数组的副本,而只是告诉它在内存中的位置可以找到其内容。
- 1d 智能指针不适用于语法 (*)++
- 在C#中处理C++指针而不使用unsafe的最佳方法
- 为什么使用 "this" 指针调用派生成员函数?
- 函数向量_指针有不同的原型,我可以构建一个吗
- 使用指针从C++中的数组中获取最大值
- 助记符和指向成员语法的指针
- 嵌入方指针压缩已禁用
- 数组的指针从不分段故障
- C++ 指针的内存地址和指向数组的内存地址如何相同?
- 何时在引用或唯一指针上使用移动语义
- QMetaObject invokeMethod的基于函数指针的语法
- 如何从 std::atomic 中提取指针 T<T>?
- 如何在 C# 中映射双 C 结构指针?
- C++将浮点指针值舍入为小数位数
- 为什么++(*p)更改指针值
- 调整大小后指向元素值的指针unordered_map有效?
- 正在将指针转换为范围
- 使用指向成员的指针将成员函数作为参数传递
- 将OpenCV C++重写为EmguCV C#-如何使用指针
- C++-试图将函数指针推回到另一个CPP文件中的矢量时出错