c++ - How do I pass an array to function by reference? -
i want pass array function reference. function dynamically allocate elements.
this code give me error message: access violation
#include <iostream> using namespace std; void func(int* ptr) { ptr = new int[2]; ptr[0] = 1; ptr[1] = 2; } void main() { int* arr = 0; func(arr); cout << arr[0] << endl; // error here }
c++ passes arguments value. if want pass int
pointer reference, need tell c++ type "reference pointer int
": int*&
.
thus, function prototype should
void func(int*& ptr);
note still not handling pointers or references arrays, rather pointer first element, close not same.
if wanted pass array of size 2
reference, function prototype this:
void func(int(&my_array)[2]);
Comments
Post a Comment