Hi, I'm recently studying the usage of dynamic array.
I have figured out how to define a dynamically sized array
and several ways to pass "INTO FUNCTION".
The question that bothers me is that
can I pass a dynamic array defined INSIDE function "BACK TO MAIN"?
E.g.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
void createArr(int* arr,size);
{
array = new array[size*10];
}
int Main
{
int *array;
createArr(array,5);
cout << "Elements in array: ";
for (int i=0;i<=50;i++)
cout << array[i] << " "; // Error
return 0;
}
I could only access the array elements inside function
but error occurs when I try to access in Main.
Can anyone tell me a proper way to pass a dynamic array
outside of the scope or whether it is viable or not?
But you still have to make sure that you don't go beyond array bounds (line 12). A size-50 array has elements indexed 0 - 49.
BTW
- it's int main(), not int Main,
- size needs a type,
- extraneous ; at the end of line 1
- using new still requires that you specify a type (here, int),
- even though it's an array, a reference (&) will be needed in the function parameter list.
#include <iostream>
usingnamespace std;
void createArr( int *&arr, int size )
{
arr = newint[size*10]; // create array
for ( int i = 0; i < size * 10; i++ ) arr[i] = 2 * i; // put in some values
}
int main()
{
int *A;
createArr( A, 5 );
cout << "Elements in array: ";
for (int i = 0; i < 50; i++ ) cout << A[i] << " ";
delete [] A; // on principle
}
#include <iostream>
usingnamespace std;
int *createArr( int size )
{
int *arr = newint[size*10]; // create array
for ( int i = 0; i < size * 10; i++ ) arr[i] = 2 * i; // put in some values
return arr;
}
int main()
{
int *A = createArr( 5 );
cout << "Elements in array: ";
for (int i = 0; i < 50; i++ ) cout << A[i] << " ";
delete [] A; // on principle
}
Lastchance, that is exactly what I need and thanks for the debugging!
So what I'm missing is pass by reference (the '&' sign),
but I cant quite grasp the principle of this.
I know passing memory address is the only way to pass value changes inside functions back to main,
but isn't array A already a pointer (stores memory address) if you define this way?
1 2 3 4 5 6 7 8 9 10 11
int main()
{
int *A; // A is a pointer type (?)
createArr( A, 5 );
cout << "Elements in array: ";
for (int i = 0; i < 50; i++ ) cout << A[i] << " ";
delete [] A; // on principle
}
Also, is the second method meaning that the returned value will be a pointer of pointer?
1 2 3 4 5 6
int *createArr( int size )
{
int *arr = newint[size*10]; // create array
for ( int i = 0; i < size * 10; i++ ) arr[i] = 2 * i; // put in some values
return arr;
}