简体   繁体   English

如何创建对使用 C++ 中的 new 运算符动态创建的数组的引用?

[英]How to create a reference to an array created dynamically using new operator in C++?

#include<iostream>
using namespace std;
int accept(int &,int );//int accept(int*,int)
int main()
{
    int n=3;
    //int arr[3]={0,1,2};
    int *marks=new int[n]; //creating an array dynamically
    //int (&ref_arr)[3]=arr;// I know how to create a reference to statically created array;
    int* &ref_marks=marks;//creating reference for array;
    accept(ref_marks,n);
    return 0;
}

int accept(int &marks,int n)
{
    int i;
    for(i=0;i<n;i++)
    {
        cin>>marks[i];
    }
    return 0;
}

Could you please help me out with creating reference to an array which is on heap area.您能否帮我创建对堆区域上的数组的引用。

You could write:你可以写:

using int3 = int[3];
int3& ref = reinterpret_cast<int3&>(*marks);

However it would be better practice to just use std::array or std::vector .但是,最好只使用std::arraystd::vector

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

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