Array Problem

Array overwriting itself

Page 1 of 1

6 Replies - 645 Views - Last Post: 20 September 2009 - 11:20 AM Rate Topic: -----

#1 Ronin32  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 8
  • Joined: 25-May 09

Array Problem

Posted 19 September 2009 - 09:34 PM

Hello,
I seem to be having a small issue with my code and I was hoping someone could help me with this.
The best way I can explain this is that I have an array ProfileArray, which holds several member profiles.
The loadProfile member function is called when the program is started. When the array is updated for the first time using the member function AddMember, within loadProfile, the 0 element is properly initialized to the member profile.

Well when the next loop is performed within the while function within loadProfile the ProfileArray 0 element is updated as newprofile1 is being initialized. Then the addMember function is called and ProfileArray 1 element is updated. So basically the second member profile overwrites the previous profile in the 0 element and then addMember is called and the 1 element is then initialized to the second member function. And there lies the error. Has anyone had to deal with this before I am stumped at this point and am not sure where to research this?
Thanks for any advice provided.


namespace nProfile
{
	public class Profile
	{
		public string sName;
		public string sRank;
		public string sInit;
		public int iID;			  
	}

}


namespace ProfCont
{
  
		
		/// <summary>
		/// Class manages an array of profiles loaded from
		/// a file at program start up
		/// </summary>
		public sealed class ProfContainer
		{

			private static int iSize = 5; //increase to 50
			private int iCount, iID, PNum;
			private Profile[] ProfileArray = new Profile[iSize+1];
			private Profile nullProf = new Profile();
			private StreamWriter output;
			private StreamReader input;
			private FileStream fs;
			private Random rand = new Random();
			
			public ProfContainer()
			{
				rand = new Random(100);

				iCount = 1;
				iID = 0;
				PNum= 0;

				nullProf.iID = 0;
				nullProf.sInit = "";
				nullProf.sName = "";
				nullProf.sRank = "";

				for (int i = 0; i < iSize+1; i++)
				{
					ProfileArray[i] = nullProf; 
					
				}
			}

			/*-----------------------------------------------------------------------------------------------------------------------------------------------------------------------*/
			/// <summary>
			/// Retrieves the singleton instance of the ProfContainer class
			/// </summary>
			public static ProfContainer Instance
			{get {return Nested.instance;}}

			class Nested
			{

				/// <summary>
				/// Explicit static constructor to tell C# compiler
				/// not to mark type as beforefieldinit
				/// </summary>
				static Nested() { }
			
				internal static readonly ProfContainer instance = new ProfContainer();
			}//end Nested


			 /*-----------------------------------------------------------------------------------------------------------------------------------------------------------------------*/
			
			/// <summary>
			/// Insert a member profile into the profile container
			/// Uses an ordered Array-Based symbol table
			/// </summary>
			/// <param name="Member"></param>

			public void AddMember(Profile Member)
			{			   
					//iID = Member.iID;
				   // while (PNum > 0 /*&& iID < ProfileArray[PNum - 1].iID*/)
				   // { ProfileArray[PNum] = ProfileArray[PNum - 1]; PNum--; }
					ProfileArray[PNum] = Member;				   
					PNum  = ++iCount;				
			}//end AddMember

			/*-----------------------------------------------------------------------------------------------------------------------------------------------------------------------*/
			/// <summary>
			/// Returns the number of profiles in the profile container
			/// </summary>
			/// <returns></returns>
			public int Count()
			{
				return iCount;
			}//end Count()

			/// <summary>
			/// Checks for array overflow
			/// </summary>
			/// <returns></returns>
			public int Overflow()
			{
				if (iCount < (iSize + 1)) return 1;
				else
					return 0;
			}//end OverFlow

			/*-----------------------------------------------------------------------------------------------------------------------------------------------------------------------*/
			/// <summary>
			/// Removes a profile from the array
			/// </summary>
			/// <param name="newProfile">
			/// Profile to be deleted
			/// </param>
			/// <returns>
			/// returns 0 if unsuccessful and 1 if successful 
			/// </returns>
			public int RemoveProfile(Profile newProfile)
			{
			   
				for(int i = 0; i < iCount; i++)
					if (ProfileArray[i].iID == newProfile.iID)
					{
						ProfileArray[i].iID = 0;
						ProfileArray[i].sInit = "";
						ProfileArray[i].sName = "";
						ProfileArray[i].sRank = "";
						iCount--;
						return 1;//success 
					}//end if
				return 0; //profile not found
			}//end RemoveProfile

			/*-----------------------------------------------------------------------------------------------------------------------------------------------------------------------*/
			/// <summary>
			/// Searches the profile array by ID
			/// </summary>
			/// <param name="newProfile"></param>
			/// <returns>
			/// returns 0 if profile not found
			/// returns 1 if profile is found
			/// </returns>
			public int SearchProfileArray(Profile newProfile)
			{
				try
				{

					for (int i = 0; i < iCount; i++)
					{
						if (newProfile.iID == ProfileArray[i].iID)
						{
							return 1; // profile ID found
						}//end if
						
					}//end for 
				}//end try
				catch (Exception ex)
				{
					MessageBox.Show(ex.ToString());
				}//end catch
					return 0;	   
			}//end SearchProfileArray


			/*-----------------------------------------------------------------------------------------------------------------------------------------------------------------------*/
			/// <summary>
			/// Searches the profile array and returns the profile if it exists
			/// </summary>
			/// <param name="iID"> ID of the profile to return</param>
			/// <returns>Returns Retrieved Profile</returns>
			public Profile SearchProfileArray(int iID)
			{
				for (int i = 0; i < iCount; i++)
				{
				   //if (ProfileArray[i].iID != iID) break;
					if (iID == ProfileArray[i].iID) return ProfileArray[i];
				}//end for
				MessageBox.Show("Profile Not Found");	 
				return nullProf;

			}//SearchProfileArray


			/*-----------------------------------------------------------------------------------------------------------------------------------------------------------------------*/	  

			/// <summary>
			/// Saves the contents to file. If the file is not 
			/// empty the contents are appended.
			/// </summary>
			/// <param name="newProf"></param>
			public void SaveProfile(Profile newProf, string saveFile)
		{
			
		   fs = new FileStream(saveFile , FileMode.Append, FileAccess.Write );
		   output = new StreamWriter(fs);
		   int iResult;
		   
		   //Generate random ID number
			do
			{
			newProf.iID = rand.Next(100,200);
			iResult = SearchProfileArray(newProf);
			}
			while (iResult != 0);
					  
			try
			{
				AddMember(newProf);
				output.WriteLine("  {0}|{1}|{2}|{3}|  \n ", 
				newProf.sName, newProf.sRank, newProf.sInit, newProf.iID);
			}//end try
			catch (Exception ex)
			{
				MessageBox.Show(ex.ToString());
			}//end catch
				   
			output.Flush();
			output.Close();
			fs.Close(); 
		}//end SaveProfile

			
			/*-----------------------------------------------------------------------------------------------------------------------------------------------------------------------*/

		/// <summary>
		/// Overrites the saved file and rewrites buffer information
		/// into a new file
		/// </summary>
		/// <param name="newProf"></param>
		public void SaveProfile(string saveFile)
		{
			
				fs = new FileStream(saveFile, FileMode.Create, FileAccess.Write);
				output = new StreamWriter(fs);

				try
				{
					for (int i = 0; i < iCount; i++)
					{
						output.WriteLine("  {0}|{1}|{2}|{3}|  \n ",
						ProfileArray[i].sName, ProfileArray[i].sRank,
						ProfileArray[i].sInit, ProfileArray[i].iID);
					}//end for
				}//end try
				catch (Exception ex)
				{
					MessageBox.Show(ex.ToString());
				}//end catch

			output.Flush();
			output.Close();
			fs.Close();
		}//end SaveProfile


		/*-----------------------------------------------------------------------------------------------------------------------------------------------------------------------*/

		/// <summary>
		/// Loads the PCF.dat file into the profile container array at load up
		/// </summary>
		public void LoadProfile(string LoadFileName)
		{
		   
			fs = new FileStream(LoadFileName, FileMode.Open);
			input = new StreamReader(fs);
			
			String line = "";
				
			try
			{
				while ((line = input.ReadLine()) != null)
				{
					Profile newProfile1 = new Profile();
					String[] strings = line.Split(new char[] { '|' });

					int i = strings.Length-2;
					int j = 0;
					
					while( j != i)
					{
						if (j == 0)
						{
							newProfile1.sName = strings[j];   
							newProfile1.sRank = strings[++j];   
							newProfile1.sInit = strings[++j];
							newProfile1.iID = Convert.ToInt16(strings[++j]);												   
						}
						else
						{							
							newProfile1.sName = strings[++j];	 
							newProfile1.sRank = strings[++j];						   
							newProfile1.sInit = strings[++j];							
							newProfile1.iID = Convert.ToInt16(strings[++j]);
						}

						AddMember(newProfile1);
					}//end while
					
					
				}//end while

			}//end try
			catch (Exception ex)
			{
				MessageBox.Show(ex.ToString());
			}//end catch
			input.Close();
			fs.Close();

		}//end LoadProfile
 

	}

}



Is This A Good Question/Topic? 0
  • +

Replies To: Array Problem

#2 gbertoli3  Icon User is offline

  • DIC at Heart + Code
  • member icon

Reputation: 40
  • View blog
  • Posts: 1,162
  • Joined: 23-June 08

Re: Array Problem

Posted 19 September 2009 - 10:56 PM

Is iID where you are storing your member id? Are you incrementing the iID?

After you have created and saved a user you should put that way you will not overwrite your data, this is assigning 1 above your iID. So if your iID was 2, then it will assign the next to be 3
iID++;



Hope this helps

This post has been edited by gbertoli3: 19 September 2009 - 10:58 PM

Was This Post Helpful? 0
  • +
  • -

#3 Ronin32  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 8
  • Joined: 25-May 09

Re: Array Problem

Posted 20 September 2009 - 07:42 AM

iID is actually a randomly generated unique identifier attached to each profile. iCount keeps track of the number of profiles that are active. But PNum and iCount do what you are suggest and I will look at those values and see if they are the problem.
Was This Post Helpful? 0
  • +
  • -

#4 Ronin32  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 8
  • Joined: 25-May 09

Re: Array Problem

Posted 20 September 2009 - 08:02 AM

I removed PNum and used iCount directly as shown in the following code and that did not solve the problem. Using the debugger to step though the LoadProfile method it seems that after the first update to the profile array and on the second loop through the method, before reaching addMember, that newProfile1 is still updating the ProfileArray. Its almost as if newProfile is referencing the last ProfileArray element used, if that makes sense.



  public void AddMember(Profile Member)
			{			   
					//iID = Member.iID;
				   // while (PNum > 0 /*&& iID < ProfileArray[PNum - 1].iID*/)
				   // { ProfileArray[PNum] = ProfileArray[PNum - 1]; PNum--; }
					ProfileArray[iCount] = Member;				   
					++iCount;				
			}//end AddMember


This post has been edited by Ronin32: 20 September 2009 - 08:07 AM

Was This Post Helpful? 0
  • +
  • -

#5 janne_panne  Icon User is offline

  • WinRT Dev
  • member icon

Reputation: 429
  • View blog
  • Posts: 1,047
  • Joined: 09-June 09

Re: Array Problem

Posted 20 September 2009 - 09:12 AM

Your constructor is wrong.

			public ProfContainer()
			{
				rand = new Random(100);

				iCount = 1;
				iID = 0;
				PNum= 0;

				nullProf.iID = 0;
				nullProf.sInit = "";
				nullProf.sName = "";
				nullProf.sRank = "";

				for (int i = 0; i < iSize+1; i++)
				{
					ProfileArray[i] = nullProf; 
					
				}
			}



After that for loop, each of your Profiles in ProfileArray reference to the same object: nullProf. So when you change one, you change them all.

I suggest you just do this in your constructor:

			public ProfContainer()
			{
				rand = new Random(100);

				iCount = 1;
				iID = 0;
				PNum= 0;

				for (int i = 0; i < iSize+1; i++)
				{
					// this
					ProfileArray[i] = new Profile();
					ProfileArray[i].iID = 0;
					ProfileArray[i].sInit = "";
					ProfileArray[i].sName = "";
					ProfileArray[i].sRank = "";
				}
			}



Would also look better if you just created an constructor which sets all those values to empty/zero instead of setting them in that for loop like I did.
Was This Post Helpful? 1
  • +
  • -

#6 Ronin32  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 8
  • Joined: 25-May 09

Re: Array Problem

Posted 20 September 2009 - 10:40 AM

Janne_panne I think you have the right idea. I think its the singleton that is causing the issue. Anything that is initialized with new Profile seems to all be set to one single reference of Profile I think.

This post has been edited by Ronin32: 20 September 2009 - 10:41 AM

Was This Post Helpful? 0
  • +
  • -

#7 Ronin32  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 8
  • Joined: 25-May 09

Re: Array Problem

Posted 20 September 2009 - 11:20 AM

janne_panne thanks for the clue. I created a test case and I had to work directly with the array instead of creating say a single profile and updating it then initializing element 0 of the array to that profile, if that makes sense. So this problem is solved.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1