When I try to do the following I get an error saying I\'m trying to read or write to protected memory.
void func1(int * ptr) {
int *ptr_b = new int[5];
You passed the pointer by value. Which means that the pointer that the function works with is a local copy of the caller's pointer. And so the value you assign in the function cannot seen by the caller.
Pass it by reference instead so that the function can assign to the caller's pointer rather than assigning to a local copy.
void func1(int* &ptr)
Or, perhaps consider returning the newly allocated pointer:
int* func1()
{
return new int[5];
}
I'd prefer the latter approach.
Change your signature to:
void func1(int *& ptr)
You're passing the pointer by value, so the outside ptr
doesn't get changed. So it's like doing
int main() { // <--- main returns int
int *ptr_a;
delete [] ptr_a;
}
which is illegal, since ptr_a
is not initialized.
No. You're making a common beginner mistake. You're not remembering that pointers are just variables that are passed by value unless you ask for a reference or pointer to them. Change the signature of your function to void func1(int *& ptr)