I'm trying to create a function that doubles the length of an dynamic array. It does so by creating a dynamic array the size of 2*n, copying all values from the old array into the new one, intitializing all the empty spots as 0 and then overwriting the old one with the new one. Here is the code:
One thing I noticed that you are missing is a delete statement. Without this you have a serious memory leak. I inserted this and found that ALL of the values now appear to be un-initialized. This means that while we are probably changing the arr array successfully, we are failing to change the address pointed to by num. Let's fix this by sending the num pointer by reference instead of making *arr a copy of the pointer. It's so meta!
Thanks Moschops for the little exercise, but Stewbond ruined it for me :( Nah joking!
Anyways, it's quite interesting. I'm passing a pointer as argument. That pointer points to an area in the heap. Now, if I pass it through the argument, it gets copied, but the copy of it should still point at the same address. Correct? I was thinking of passing it by reference, but I didn't think it would make a difference.
The other peculiar thing which I don't understand is the initialization of my temp array. I mean no matter what I pass as argument in the feature, it should initialize the last few elements with a 0. If someone could explain to me in detail what's going?
copy of it should still point at the same address. Correct?
Yes, the copy points to the same address. And then you change that copy... and then when the function ends the copy is destroyed and you're left with the unchanged original, still pointing at the FIRST array, and not pointing a t the new, bigger array.
If you pass that pointer by reference, when you change it, and the function ends, you will have changed the original.
it should initialize the last few elements with a 0.
It does. You're not looking at them. You're looking at some random bytes off the end of your first, original, small array.