dynamic array growth

i am a high school student and my teacher suggested i put this problem on here. we are writing a program on dynamic memory growth in arrays. when we get to capacity 64 the program crashes and sends out junk. Any suggestions?
#include<iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int add_to_array(int my_array[],int new_value,int orig_lenght,int positiontoAdd);
int main()
{
int size=1;
int arr[1] = {1};
int ctr=2;
int loopthismanytimes=10;

for (int i=1;i<loopthismanytimes;i++)
{

srand(time(0));
int randNumber = (rand()%6)+1;
//cout <<"random number is "<<randNumber<<endl;

int result=add_to_array(arr,randNumber,size,ctr);
size=result;

cout <<"doubled size is "<<result<<endl;
ctr=ctr+1;

}


cout <<"now printing out the array"<<endl;
for (int i=0;i<loopthismanytimes;i++)
{
cout<<arr[i]<<endl;
}

cout<<"last doubled size is "<<size<<endl;
return 0;
}
int add_to_array(int my_array[],int new_value,int orig_length,int positiontoAdd)
{

//need to check array is full... if not add the random number
if (positiontoAdd>orig_length)
{
int* bigger_array=new int[orig_length*2];
for (int i=0;i<orig_length;i++)
{
bigger_array[i]=my_array[i];
}
delete[] my_array;
my_array=bigger_array;
my_array[positiontoAdd]=new_value;
int new_size=orig_length*2;
return new_size;
}
else //array is not full just add it
{
my_array[positiontoAdd]=new_value;
return orig_length;
}
}
code blocks. windows enviorment
You have a few problems here:

Line 34: The problem is your declaration of add_to_array:
 
int add_to_array(int my_array[],int new_value,int orig_length,int positiontoAdd)

my_array gets passed as a pointer by value. At line 42, you're attempting to change the my_array pointer to the newly allocated array.
my_array=bigger_array;
Because the my_array pointer was passed by value, you're changing the value of the local pointer, not the pointer to the array in main(). Two solutions to this. 1) Pass a pointer to my_array by reference. 2) Return the new pointer as the return value from the function (make newsize an argument passed by reference).

Line 9: You're declaring arr as a direct array which is allocated on the stack, not the heap. You can't delete an array which is on the stack (line 41). You will get a run time crash.

Line 14: You're calling srand() in the wrong place. NEVER call srand() from inside a loop. srand() seeds the random number generator. When you call srand() inside a loop, you're causing the RNG to be reset to the same point on every call within the same second. Call srand() ONCE at the beginning of main().

PLEASE USE CODE TAGS (the <> formatting button) when posting code.
It makes it easier to read your code and also easier to respond to your post.
http://www.cplusplus.com/articles/jEywvCM9/
Hint: You can edit your post, highlight your code and press the <> formatting button.

Last edited on
Topic archived. No new replies allowed.