Lets write your code with a little bit different style:
#include <iostream>
void function( int* Array)
{
Array = new int[5];
for(int i = 0; i < 5; i++)
Array[i] = 0;
}
int main(int argc, char* argv[])
{
int* Array = NULL;
function(Array);
Array[3] = 2;
system("PAUSE");
return 0;
}
(just put the * close to int, so that it is clear that
int*
is a type name)
and now compare it to this one:
#include <iostream>
void function( int val)
{
val = 5;
}
int main(int argc, char * argv[])
{
int val =0;
function(val);
std::cout << val << std::endl;
system("PAUSE");
return 0;
}
Are you surprised in seeing "0" as a result, instead of 5?
Now, your
function
, int* array is a value of type "pointer to int", that -on function call- points to the same location as the main Array (NULL in this case) but, inside function you changed the pointer to point to something else (
new int[5]
, in your case), than you assign values to the pointed array.
But inside your function there is nothing that makes
main
to now about the change you did:
Array
, in main is still pointing to NULL, and you try to write int
NULL+2
.
To solve the problem you should allocate in main, than call
function
, and inside the function, use the pointer to assign the values to the elements.
Or, pass a reference to the pointer (so that if you change it, the "original" is also changed:
#include <iostream>
void function( int*& Array)
{
Array = new int[5];
for(int i = 0; i < 5; i++)
Array[i] = 0;
}
int main(int argc, char * argv[])
{
int * Array = NULL;
function(Array);
Array[3] = 2;
system("PAUSE");
delete[]Array;
return 0;
}