C++ 使用指针传递动态创建的数组

标签 c++ arrays pointers

希望得到一点 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/

相关文章:

c++ - C++ 中的 Bash 输入/输出

javascript - 将多个数组插入有序的对象数组中

javascript - 从 JavaScript 中的另一个对象数组替换一个对象数组的值

c++ - 在 C++ 中遍历树期间指针发生变化

c++ - 混合使用 UNICODE 和非 UNICODE 翻译单元是否安全?

c++ - 这个 C++ 列表有什么问题?

c - 为什么我不能像 C 中的指针一样对待数组?

C - malloc 的返回值可以像数组一样使用(对齐)吗?

c++ - 无法存储标准输入状态并在 C++ 中进行比较

jquery - 完全删除 JSON 中的行