Quantcast

Jump to content


Photo

Resizing dynamic arrays in C++


  • Please log in to reply
12 replies to this topic

#1 Melchoire

Melchoire
  • 5284 posts


Users Awards

Posted 08 November 2009 - 09:04 PM

So I have this program that keeps prompting the user for input. For every input I have to store it inside an array but in order to do that I have to resize the array constantly. And it's the part I'm stuck on. I can't just make a huge array either.

This is the code I have now but it freezes up after the first input:
#include <iostream>

using namespace std;

void main(void)
{
	int* myArray = NULL;
	int* myNewArray = NULL;
	int i = 0;
	int input = 0;
	bool breakLoop = false;

	while(!breakLoop)
	{
		cout << "Enter a positive integer: " << endl;
		cin >> input;
		i++;
		if(input > 0)
		{
			myNewArray = new int[i];
			for(int x = 0; x < i; x++)
			{
				myNewArray[x] = myArray[x];
			}
			myNewArray[i-1] = input;
		}
		breakLoop = input < 0; 
	}
	for(int j = 0; j < i; j++)
	{
		cout << myArray[j] << endl;
	}

	delete [] myArray;
}


If it helps this is a computing science lab. Here's the webpage for it, it's problem #2:
http://www.cs.sfu.ca.../lab8/lab8.html

Edited by Melchoire, 08 November 2009 - 09:07 PM.


#2 Hydrogen

Hydrogen
  • Neocodex Co-Founder

  • 22213 posts


Users Awards

Posted 08 November 2009 - 10:50 PM

You've run into one of the more annoying problems in computer science :p. Unfortunately, as you have found out, you can't just add to an array and expect it to resize :(. In fact, looking over your program, I see that on each addition of a number, what you are actually doing is creating a new array (without deleting the previous one - memory leak) and copying the contents of a backup array over. This is pretty slow and there is a better way :p.

Have you learned about linked lists yet? They are essentially an array but resize as you add/remove from them. If you haven't learned about them yet, then you can read up on them online. If you are allowed to use the STL (Standard Template Library) in your programs, then you can just do something like
#include <list>
Which will give you access to a pre-made linked list. However, I suggest you implement your own for practice.

I'm not sure where you are in your studies so if you let me know, I can help you more :). Let me know if you need anything else :D.

#3 Melchoire

Melchoire
  • 5284 posts


Users Awards

Posted 08 November 2009 - 10:55 PM

You've run into one of the more annoying problems in computer science :p. Unfortunately, as you have found out, you can't just add to an array and expect it to resize :(. In fact, looking over your program, I see that on each addition of a number, what you are actually doing is creating a new array (without deleting the previous one - memory leak) and copying the contents of a backup array over. This is pretty slow and there is a better way :p.

Have you learned about linked lists yet? They are essentially an array but resize as you add/remove from them. If you haven't learned about them yet, then you can read up on them online. If you are allowed to use the STL (Standard Template Library) in your programs, then you can just do something like

#include <list>
Which will give you access to a pre-made linked list. However, I suggest you implement your own for practice.

I'm not sure where you are in your studies so if you let me know, I can help you more :). Let me know if you need anything else :D.

unfortunately we're not allowed to use those yet. which is pretty retarded. but she did give some specific instructions:


Increment your counter, presentsize

ii. Allocate a new dynamic array with length presentSize elements pointed to by your pointer myNewArray

iii. Place the integer that was just read in the last location of the new array

iv. If there are existing elements in myArray copy them to the same locations in myNewArray.

v. If there are elements in myArray deallocate the array myArray

vi. Make the pointer myArray point at the array myNewArray

vii. Make the pointer myNewArray point nowhere




Isn't that what I'm basically doing in the program? Except 4 & 5.




#4 Hydrogen

Hydrogen
  • Neocodex Co-Founder

  • 22213 posts


Users Awards

Posted 08 November 2009 - 11:23 PM

Yeah, that's what you are doing, but that is an utterly retarded way to do it. The only thing I would suggest is to delete the previous array before creating a new one here: myNewArray = new int[i];

#5 Melchoire

Melchoire
  • 5284 posts


Users Awards

Posted 08 November 2009 - 11:26 PM

Yeah, that's what you are doing, but that is an utterly retarded way to do it. The only thing I would suggest is to delete the previous array before creating a new one here: myNewArray = new int[i];


After I declare a new array I need to copy the old one into the new one. So that would erase the old stuff.

#6 Hydrogen

Hydrogen
  • Neocodex Co-Founder

  • 22213 posts


Users Awards

Posted 08 November 2009 - 11:29 PM

After I declare a new array I need to copy the old one into the new one. So that would erase the old stuff.

Yeah, but it seems like you are copying from myArray to myNewArray. That means that you have an array which just gets overwritten with a new pointer but the memory you allocated in the previous iteration of the while loop is still allocated to your process, even though you are no longer referencing it. It's not a big deal right now but you will probably learn about good memory management techniques really soon :p.

#7 Melchoire

Melchoire
  • 5284 posts


Users Awards

Posted 09 November 2009 - 12:12 AM

Yeah, but it seems like you are copying from myArray to myNewArray. That means that you have an array which just gets overwritten with a new pointer but the memory you allocated in the previous iteration of the while loop is still allocated to your process, even though you are no longer referencing it. It's not a big deal right now but you will probably learn about good memory management techniques really soon :p.


I'm dreading it already. :p But is there anything wrong with the code I'm using, I mean if those are her instructions there's probably a way to do it despite being needlessly complicated.

I wrote the same code with the linked list you were talking about.
void main(void)
{
	list<int> myList;
	bool breakLoop = false;
	int input = 0;
	int i = 0;

	while(!breakLoop)
	{
		cout << "Enter a postive enter. Enter 0 or less to terminate input sequence: " << endl;
		cin >> input;

		if(input > 0)
		{
			myList.push_back(input);
		}

		breakLoop = input <= 0;
	}

	cout << "The integers you input are: " << endl;

	for(list<int>::iterator j = myList.begin(); j != myList.end(); j++)
	{
		//print each iteration of mylist. in this case j is a pointer and we print the value it's pointing at
		cout << *j << endl;
	}
}

works like a charm. honestly sometimes i wonder what real programmer would think of this class. we did our midterm on paper!

#8 Hydrogen

Hydrogen
  • Neocodex Co-Founder

  • 22213 posts


Users Awards

Posted 09 November 2009 - 12:18 PM

That code looks good! I had to do my midterms on paper as well and I always thought it was weird too since a large part of the programming process is debugging and you can't debug on paper. No one expects you to get it right the first time around in the real world and that essential skill isn't adequately tested when you take an exam on paper. At least not when you code :p.

#9 Andy

Andy
  • 226 posts

Posted 11 November 2009 - 02:23 AM

#include <cstdlib>
#include <iostream>
#define forever for(;<img src='http://www.neocodex.us/forum/public/style_emoticons/<#EMO_DIR#>/wink.gif' class='bbc_emoticon' alt=';)' />
using namespace std;

int main()
{
    int* myArray = (int*)malloc(0); // Allocate myArray size of 0
    int first = NULL; //Wierd as, but realloc screws up the first position in an
    		      //array (at least in gcc), so we also have to grab that.
    int num = 0; //This will count number of times an integer is entered
    int input = 0; //Stores input temporarily before moved to array

    forever //I love forever it's defined above.
    {
        cout << "Enter a positive integer: ";
        cin >> input;
        if (input < 1) break; // Zero is not a positive number, therefore 1 is
		              // the lowest possible positive integer.
        if (!first) first = input; //If this is first input 
        num++;
        //realloc() reallocates memory in an array to have a different size
        //returns NULL on failure
        if (realloc((void*)myArray,(num)*sizeof(int))==NULL)
        {
            cout << "Error could not reallocate memory\n";
            system("PAUSE");
            return false;
        }
        myArray[num-1] = input; //Now we can enter the input into the array!
    }
    myArray[0] = first; //Resets first item in array to original value
	
    cout << endl << "You entered" << endl;
    if (!num) cout << "Nothing!" << endl; //Always good to do this check
    for (int i=0;i<num;i++)
        cout << "myArray[" << i << "]: " << myArray[i] << endl;		
    delete [] myArray; //Free up memory used by array.
    system("PAUSE"); //gcc only, don't include in VC++
    return EXIT_SUCCESS;
}
A+ :p
You really don't need STL for something as simple as this. Try keeping things simple.

Compact Version:
#include <iostream>
#include <cstdlib>
int main()
{
    int* myArray = (int*)malloc(0);
    int input,i,first=0,num=0;	
    for (;<img src='http://www.neocodex.us/forum/public/style_emoticons/<#EMO_DIR#>/wink.gif' class='bbc_emoticon' alt=';)' />
    {
        std::cout << "Enter a positive integer: ";
        std::cin >> input;
        if (input < 1) break;
        if (!first) first = input;
        num++;
        if (realloc((void*)myArray,num*sizeof(int)) == NULL) return 0;
        myArray[num-1] = input;
    }
    myArray[0] = first;
    std::cout << std::endl << "You entered \n";
    if (!num) std::cout << "Nothing! \n";
    for(i=0;i<num;i++) std::cout<<"myArray["<<i<<"]: "<<myArray[i]<<std::endl;
    delete [] myArray;
    system("PAUSE");
    return EXIT_SUCCESS;
}
A++ 24 Lines :)

Edited by Andyops, 11 November 2009 - 04:53 PM.


#10 jim2

jim2
  • 2 posts

Posted 07 November 2010 - 11:24 PM

yo I am doing this stupid lab too ! anyone can help me ? I encountered the same problem as melchorie, but this time i really need to do it without include <list> or <stdlib> just regular <iostream>

#11 Melchoire

Melchoire
  • 5284 posts


Users Awards

Posted 07 November 2010 - 11:51 PM

yo I am doing this stupid lab too ! anyone can help me ? I encountered the same problem as melchorie, but this time i really need to do it without include <list> or <stdlib> just regular <iostream>


Word up? Do you go to sfu?

#12 jim2

jim2
  • 2 posts

Posted 08 November 2010 - 11:55 AM

Word up? Do you go to sfu?


YEAH, first year engineer at SFU, I try desperately solving this lab but every time I tried I failed : (

That's why I googled her question and wondered into this site, registered as a member, and saw your post LOL.

And you must be a second year, since ur post is from Nov 8 2009 LOL

Is there any one can help mee?

it due today .... I guess it is too late

#13 Melchoire

Melchoire
  • 5284 posts


Users Awards

Posted 08 November 2010 - 04:06 PM

YEAH, first year engineer at SFU, I try desperately solving this lab but every time I tried I failed : (

That's why I googled her question and wondered into this site, registered as a member, and saw your post LOL.

And you must be a second year, since ur post is from Nov 8 2009 LOL

Is there any one can help mee?

it due today .... I guess it is too late


Haha, small world. Funny thing is, last year I posted a calc question on some random forum and some guy said he had the same question due at the same time. Turned out he was in my class. :p


1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users