#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2013
    Posts
    101
    Rep Power
    0

    Dynamic allocation


    Code:
    #include <iostream>
    
    using namespace std;
    
    int main()
    {
    	cout << "Pick # of numbers" << endl;
    	int i = 0;
    	cin >> i;
    	int *data = new int[i + 1];
    	cout << "Pick " << i << " numbers" << endl;
    	int x = 0;
    	int j = 0;
    	for(x;x < i;x++)
    	{
    		cin >> j;
    		data[x] = j;
    	}
    	for(x = 0;x <= i - 1;x++)
    	{
    		cout << *data << endl;
    		data++;
    	}
    	delete[] data;
    	getchar();
    }
    I've been having a little struggle here for the past few days of completely understanding dynamic allocation. This program works but the executable file doesn't exit properly. After it displays the results on the screen it pauses and doesn't execute the delete[] data line. Why? I can't tell if it does and it just takes a lot of time to remove data values out of the heap or it just freezes when it gets there. Why doesn't it exit properly?
  2. #2
  3. Banned ;)
    Devshed Supreme Being (6500+ posts)

    Join Date
    Nov 2001
    Location
    Woodland Hills, Los Angeles County, California, USA
    Posts
    9,638
    Rep Power
    4247
    That's because you've moved what data was pointing to originally. Instead of this:
    Code:
    	for(x = 0;x <= i - 1;x++)
    	{
    		cout << *data << endl;
    		data++;
    	}
    try this instead:
    Code:
            int *data2 = data;
    	for(x = 0;x <= i - 1;x++)
    	{
    		cout << *data2 << endl;
    		data2++;
    	}
    Now data continues to point to the memory block that you allocated and data2 is the one that is being moved. Therefore, when you do a delete[] data afterwards, it will correctly delete the block of memory that you allocated.
    Up the Irons
    What Would Jimi Do? Smash amps. Burn guitar. Take the groupies home.
    "Death Before Dishonour, my Friends!!" - Bruce D ickinson, Iron Maiden Aug 20, 2005 @ OzzFest
    Down with Sharon Osbourne

    "I wouldn't hire a butcher to fix my car. I also wouldn't hire a marketing firm to build my website." - Nilpo
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2013
    Posts
    101
    Rep Power
    0
    Thank you scorpions. My mistake :o

IMN logo majestic logo threadwatch logo seochat tools logo