Assigning values to Dynamically Allocated Array Problem

Hi,

I'm having some issues assigning values to a dynamically allocated array immediately after a row of the array has been created. When printing the output of the array inside the "creation loop" (after the assignment of a value to the newly created array element), the output is correct but when printing outside the "creation loop", the output is garbage. Is there something in the standards of C or C++ that says you can't do something like this?

Here's some example code that illustrates this problem:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
	int *exampleArray;
	
	cout << "Array output inside creation loop..." << endl;
	for(int i = 0; i < 10; i++)
	{
		exampleArray = new int;
		exampleArray[i] = i;
		cout << exampleArray[i] << endl;
	}
	
	cout << endl << "Array output outside creation loop..." << endl;
	for(int i = 0; i < 10; i++)
		cout << exampleArray[i] << endl;
	
	delete exampleArray;


Here's the output:
Array output inside creation loop...
0
1
2
3
4
5
6
7
8
9

Array output outside creation loop...
0
0
0
135073
8
0
0
0
0
9


Thanks in advance for any help!
Ouch! You are allocating just enough memory for one int, not an array of int's. Then you are storing values into unallocated memory. Then you reallocating memory without deallocation the old memory.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
int *exampleArray;
	
cout << "Array output inside creation loop..." << endl;
exampleArray = new int[10]; //allocate enough memory for 10 int's
for(int i = 0; i < 10; i++)
{
	// exampleArray = new int;
	exampleArray[i] = i;
	cout << exampleArray[i] << endl;
}

cout << endl << "Array output outside creation loop..." << endl;
for(int i = 0; i < 10; i++)
	cout << exampleArray[i] << endl;

delete exampleArray;
Last edited on
Mathhead200-

Thanks for pointing that out! I must not have been paying close enough attention to my professor when he covered dynamic allocation of memory :).
No prob. Just remember for each new, you need a delete...
So for 10 news in a loop, you need 10 deletes (most likely also in a loop.)
Last edited on
http://www.cplusplus.com/forum/general/39813/#msg215623
Allocated with new unallocated with delete
Allocated with new [] unallocated with delete []
Topic archived. No new replies allowed.