I am trying to allocate memory in a function and I am not sure what I am doing wrong. I want this:
int main()
{
int* test= 0;
initialize(test, 10);
int test2 = test[2];
delete[] test;
}
void initialize(int* test, int count)
{
test = new int[count];
for (int i = 0; i < count; i++)
{
test[i] = i;
}
}
But I receive this error: Unhandled exception at 0x770d15de in Robust Simulation.exe: 0xC0000005: Access violation reading location 0x00000008. It breaks on line: int test2 = test[2];
but this works:
int main()
{
int* test=0;
test = new int[10];
for (int i = 0; i < 10; i++)
{
test[i] = i;
}
int test2 = test[2];
delete[] test;
}
Is there a scoping problem? I thought since I pass it a pointer it would be allocated and I would be able to access it outside of the initialize function.
Thanks for your help
Do following changes:-
initialize(&test, 10);
....
void initialize(int** test, int count)
{
*test = new int[count];
for (int i = 0; i < count; i++)
{ (*test)[i] = i; }
}
C++ has another feature called references if you want as it is :-
void initialize(int*& test, int count)
{
test = new int[count];
for (int i = 0; i < count; i++)
{ test[i] = i; }
}
what you are doing is passing the test[from main](address will pass) and storing in another local pointer variable named test.This new variable has lifetime of function scope and will get soon deleted leaving garbage after the completion of function.
Another option is
int* test= initialize(test, 10);
and change initialize as
int* initialize(int* test, int count)
{
test = new int[count];
for (int i = 0; i < count; i++)
{ test[i] = i; }
return test;
}