Advertisement

Problem with pointers

Started by November 26, 2001 02:14 PM
1 comment, last by Jeff D 23 years ago
Well to start off I was practicing makeing classes so I wanted to make a class that held an array of random ints. So I came up with this:
      
class ints
{

   public:


   private:
      int numOfInts;
      int intArray[numOfInts];
};
  
well I found out fast that C++ does not allow an array that does not give a constant number because it might be zero( and I guess negative also). So for a while I played with the syntax but never worked. So after a while I thought hey maybe I should make a pointer and point to another ints. And the code looks like this:
        
#include <iostream.h>

class linkedint
{

	public:	

		linkedint()
		{

			nextint = 0;
			SetInt(0);
			
		}

		linkedint(int idnum)
		{

			nextint = 0;
			SetInt(idnum);
							
		}

		void SetInt(int idnum)
		{

			id = ++idnum;
			cout << "Input a number. -99 to end.  ";
			cin >> num;
			if(num != -99)
				NextInt();
			cout << endl;
			
			
		}
		~linkedint() 
		{ 
		
			delete nextint; 
		
		}
		void PrintLinkedInt()
		{

			cout << id << " " << num << endl;
			if(nextint != 0)
				nextint->PrintLinkedInt();
			
		}

		void NextInt()
		{

			nextint = new linkedint(id);

		}

	private:
		int id;
		int num;
		linkedint* nextint;
		
};

linkedint li;

int main()
{

	li.PrintLinkedInt();
	return 0;

}
  
Now this worked exactly how I wanted it to. Im guessing this is a linked list that why I named it linkedint. After a while tho I thought that what if I wanted to delete one of the ints in the middle or even the first one. So I thought of making a pointer that pointed to the prevoius linkedint and when I wanted to delete one of the middle ones I could somehow give the address to the one after the one I want to delete and pass it over to the previous one. I deleted the code so I could show you the above code. But it was bad code neways. Is there an easy way to do this?? Thx, Jeff Desrosiers Edited by - Jeff D on November 26, 2001 3:16:10 PM Edited by - Jeff D on November 26, 2001 3:17:52 PM
Suffered seven plagues, but refused to let the slaves go free. ~ Ross Atherton
This has nothing to do with linked lists, but there IS a way to have dynamically-sized arrays. Try this:

int numOfInts;
int * arrayOfInts;

arrayOfInts = new int[numOfInts];

and then when you''re finished with the array:

delete [] arrayOfInts;

Hope this helps.

---------------

I finally got it all together...
...and then forgot where I put it.
Advertisement
Yes, you can use the std::vector type, which is a resizable array.

http://www.sgi.com/tech/stl/
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan

This topic is closed to new replies.

Advertisement