希望得到一点 C++ 帮助——我对这个话题还很陌生。我试图根据用户输入的指针动态创建一个数组,然后将该数组传递给一个函数。但是指针(以及数组)传递感觉有点不对劲,因为没有发生取消引用。
在传递期间/之后,我们是否只是将指针视为任何正常声明和传递的数组,而不需要取消引用 (*) 任何东西?还是我应用不正确?
伪代码如下:
#include<iostream>
using namespace std;
void arrayFunc(int [], int); // << Note no indication of pointer pass
int main()
{
int *arrayPtr = 0; // Array pointer
int arrayElem = 0; // Number of elements in array
cout << "\nPlease enter the number of elements: ";
cin >> arrayElem;
arrayPtr = new int[arrayElem]; // Dynamically create the new array
arrayFunc(arrayPtr, arrayElem); // << Note no dereferencing or other indication of pointer
return 0;
}
void arrayFunc(int array[], int arrayElem) // << Same here - now it's just a plain old array
{
// All the functiony-bits go here, referencing array without the need to dereference
}
[编辑] 虽然上面的代码有效,但以下包括在下面的讨论中确定的修复:
#include<iostream>
using namespace std;
void arrayFunc(int*, int); // Changed to pointer pass instead of []
int main()
{
int *arrayPtr = 0; // Array pointer
int arrayElem = 0; // Number of elements in array
cout << "\nPlease enter the number of elements: ";
cin >> arrayElem;
arrayPtr = new int[arrayElem]; // Dynamically create the new array
arrayFunc(arrayPtr, arrayElem);
return 0;
}
void arrayFunc(int* array, int arrayElem) // Passing a pointer now instead of []
{
// All the functiony-bits go here, referencing array without the need to dereference
}
最佳答案
你应该在你的函数中传递指针,因为它准确地描述了情况,即你正在传递一个动态分配的内存。 arrayPtr
本质上是指向数组第一个元素的指针。因此,您无需担心取消引用它。
将函数签名更改为:
void arrayFunc(int*, int);
关于C++ 使用指针传递动态创建的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31345138/