繁体   English   中英

C ++通过指针传递动态创建的数组

[英]C++ Passing a Dynamically Created Array with 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
}

您的尝试是正确的。 您正在按值传递数组指针。 然后,您可以在arrayFunc正常取消引用

您应该在函数中传递指针,因为它可以准确描述情况,即传递动态分配的内存。 arrayPtr本质上是指向数组第一个元素的指针。 因此,您不必担心取消引用它。

将功能签名更改为:

void arrayFunc(int*, int);

C的设计是假装一个指针和一个数组几乎是同一回事。 因此,许多简单的用法都比较容易。 但是,当您考虑指向数组的指针时,该概念变得更加混乱。 感觉这不应该与指向该数组第一个元素的指针相同,但是在分配内存和使用指针的通用方法中,指向数组的指针实际上只是指向该数组的第一个元素的指针数组。

我发现最好将“指向数组的第一个元素的指针”视为C中*的正常含义。指向标量对象的特殊情况是将标量有效地视为数组的第一个(也是唯一的)元素长度为1。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM