Hello. Can anyone help me out please.
I'm trying to dynamically grow an array.
Below is the function which I call from main when an array (also dynamically
allocated in main)gets filled up. I'm not even shure where the problem occurs.
When I print out the new array I find that in the first two positions there are
zerows instead of the values that should've been copied from old array.
Strangely enough, the rest of the values are being copied fine.
Line 8 doesn't actually change the array outside of the function.
Why are you doing things the hard way? You should use std::vector - never deal with pointers or memory management. If you have to use new, delete, malloc, or free, you're doing something very wrong.
So, what does exactly line 8 do? I thought it sets the value of parr pointer to have the value
of temp pointer. And if I'm not mistaken, an array allocated inside an function is still available
at a higher level. In main.
Besides, why do the rest of the values get copied fine?
Second, that int parr[] is misleading; free takes address of dynamically allocated memory rather than of just any array. To answer the question, pointer parameters are by value parameters.
Lets write:
1 2 3 4 5 6 7 8 9
void foo( int * bar ) {
int x = 42;
*bar = 7;
bar = &x;
}
// used in:
int * gaz = 0xff;
foo( gaz );
Now we inline the call, as pseudocode:
1 2 3 4 5 6 7 8 9 10
int * gaz = 0xff;
{
int * foo_bar;
int foo_x;
foo_bar = gaz; // bar is a copy of gaz; both hold address 0xff
foo_x = 42;
*foo_bar = 7; // write 7 to location 0xff; assert( *gaz == 7 )
foo_bar = &foo_x; // foo_bar has address of foo_x; *foo_bar==42; *gaz==7
} // foo_bar and foo_x are removed from stack
// gaz==0xff, *gaz==7
In order to solve the dilemma, we add indirection:
1 2 3 4 5 6
void foo( int* * bar ) {
int x = 42;
**bar = 7; // bar is a pointer to location of "gaz", this line does same as *gaz=7
*bar = &x; // *bar returns gaz, so this line does same as gaz=&x
}// x leaves scope, gaz points to deallocated memory
// *bar = malloc(666); would have been fine
In other words, a pointer parameter allows modifying value of the caller. If the value that we want to modify is a pointer, we have to pass a pointer to that pointer to the function.
Note: The realloc() returns a new pointer rather than modifies input parameter.