I'm starting to learn C++ and I decided to create a simple program using dynamic memory from the tutorial on this website just for practice.
But I don't know why my program shows an error sometimes and other times it runs fine. I would like an explanation and how I can fix it.
Here is my code:
int i = 0;
int c = 0;
int * dynamicArray;
dynamicArray = new (nothrow)int[i]; //new int
for(i=0; c==0 ; i++)
cout << "Input value for Array #" << i << ": ";
cin >> dynamicArray[i]; //invalid access
The array does not automagically resize.
> why my program shows an error sometimes and other times it runs fine.
undefined behaviour is undefined
Also, consider using meaningful names for the variables.
On line 11, you're allocating an array of "i" integers. However, prior to the allocation on line 11, "i" has a value of zero and does not change. Therefore, on line 11, you're allocating zero integers. Strangely enough, the compiler permits this, and "new" actually gives you a pointer, but that does not mean you actually allocated memory; thus, attempting to access the dynamically-allocated memory will generate a run-time exception.
Before allocating your memory, ensure that "i" is a value greater than zero.
Okay, but I still don't get it. What do I need to do to fix it?
I tried changing line 11 to: dynamicArray = new (nothrow)int[i];
But I still have the same problem. The program runs sometimes and other times stops during running.
I also tried changing the loop so it starts at 1 instead of 0, but same result.
You're only defining your array to have memory for a single element. Yet, in your loop, you're allowing the user to enter more than one number, in which case it will attempt to store more than one element in your array. Which means you're attempting to write beyond the bounds of the array, leading to undefined behaviour (but, very likely, your program crashing).
You'd be much better off using vectors instead of C-style arrays.