14 Replies - 3047 Views - Last Post: 03 March 2010 - 10:34 AM Rate Topic: -----

#1 Guest_Kae*


Reputation:

dynamic array within a class

Posted 01 March 2010 - 09:32 PM

I am having a problem with a dynamic array placed within a class.

 VOTER :: VOTER (string ID, string results)
	{
		int vrSize;
		voterID = ID;
		voteResults = results;

		vrSize = voteResults.size();

		// Create dynamic array
		voteArray = new char [vrSize];

		// Populate array with results from string results
		for (int i = 0; i < voteResults.size(); i++)
		{
			voteArray [i] = voteResults.at (i);
		}

		// Print array
		/*for (int i = 0; i < voteResults.size(); i++)
		{
			cout << voteArray [i] << " ";
		}
		cout << endl;*/
	} 


When tested with the Print array (which is currently commented out), it prints out fine. However, when I run the program in debug, the array shows an error. Specifically, this creates a voter number "4015", a vote result of "BDFIJ" and an array that looks like "0x003377f0 "BDFIJ yyyy *some random characters*". Can anyone tell me what I'm doing wrong? I need this dynamic array, as the voter numbers and results are being read in from a file and may change in length.

It may also help to know that this class compiles separately. If you need the code from another area of the program (i.e. main), let me know and I will put it up.

Much Mahalos!

~K

Is This A Good Question/Topic? 0

Replies To: dynamic array within a class

#2 jjl   User is offline

  • Engineer
  • member icon

Reputation: 1270
  • View blog
  • Posts: 4,998
  • Joined: 09-June 09

Re: dynamic array within a class

Posted 01 March 2010 - 09:43 PM

is voteResults a string vector? if it is then your trying to assign string values to each index in your char array
Was This Post Helpful? 0
  • +
  • -

#3 Guest_Kae*


Reputation:

Re: dynamic array within a class

Posted 01 March 2010 - 09:53 PM

View PostImaSexy, on 01 March 2010 - 08:43 PM, said:

is voteResults a string vector? if it is then your trying to assign string values to each index in your char array


Maybe I misunderstood this in class, but I thought that string was a character array, and that using the .at () function returned a character at the location between the (). Wouldn't assigning string values to a char array also have caused an error in the compilation? This program compiles fine, but it doesn't run right when I try to access the array later. Says something about <badptr>.

Am I understanding this wrong?

Much Mahalos for your help,

~K
Was This Post Helpful? 0

#4 sarmanu   User is offline

  • D.I.C Lover
  • member icon

Reputation: 967
  • View blog
  • Posts: 2,362
  • Joined: 04-December 09

Re: dynamic array within a class

Posted 01 March 2010 - 10:05 PM

vrSize = voteResults.size();

// Create dynamic array
voteArray = new char [vrSize];

// Populate array with results from string results
for (int i = 0; i < voteResults.size(); i++)
{
     voteArray [i] = voteResults.at (i);
}


So, vrSize is actually voteResults length, why don't you use it in the for loop? Why are you still using voteResults.size()? Here's how I would do this:
vrSize = voteResults.size();

// Create dynamic array
voteArray = new char [vrSize + 1]; // just overallocate with +1, be sure that everything's OK

if (voteArray == NULL) // check if memory allocation succeeded
   throw bad_alloc("mem. allocation failed\n");

// Populate array with results from string results
for (int i = 0; i < vrSize; i++)
{
     voteArray[i] = voteResults[i]; // just get rid of .at()
}

voteArray[vrSize] = '\0'; // append null terminator


This post has been edited by sarmanu: 01 March 2010 - 10:07 PM

Was This Post Helpful? 0
  • +
  • -

#5 jjl   User is offline

  • Engineer
  • member icon

Reputation: 1270
  • View blog
  • Posts: 4,998
  • Joined: 09-June 09

Re: dynamic array within a class

Posted 01 March 2010 - 10:07 PM

ok so its just a string. Thats fine, you can also just use [] (brackets) instead of the the at function to get a char from a string at a specific index.

But badptr is a bad pointer, so I think you getting a bad allocation. Try this
VOTER :: VOTER (string ID, string results)
{
	int vrSize;
	voterID = ID;
	voteResults = results;

	vrSize = voteResults.size(); //check the size of this

	try
	{
		voteArray = new char [vrSize+1]; //add space for null character 
	}
	catch(bad_alloc &al)
	{
		cerr<<"BAD ALLOCATION "<<al.what()<<endl;
	}

	// Populate array with results from string results
	for (int i = 0; i <vrSize; i++)
	{
		voteArray[i] = voteResults[i];
	}

	for (int i = 0; i < vrSize; i++)
	{
		cout << voteArray[i] << " ";
	}
	cout << endl;
} 


This post has been edited by ImaSexy: 01 March 2010 - 10:08 PM

Was This Post Helpful? 0
  • +
  • -

#6 Guest_Kae*


Reputation:

Re: dynamic array within a class

Posted 01 March 2010 - 10:38 PM

Thanks guys! Allocating the memory the CORRECT way fixed it! During debug, I no longer get the funny character filled array.

I thought that problem explained why my vector holding each class object was failing, but its still failing. This is where I get the <bad ptr> designation.

while (!voters.eof())
	{
		// Read in id
		voters >> id;
		// Read in votes
		voters >> votes;
		// Initiate object of VOTER
		VOTER v (id, votes);
		// Store object in the vector
		storeVoters.push_back (v);
 	}


When it pushes into the vector, the array portion reads: "0xcdcdcdcd <Bad Ptr>"

Any ideas? As I mentioned, I thought my only problem was the array.

Much Much MUCH Mahalos for your help so far and for all future help! I'm just not understanding what the problem is in the code.

~K
Was This Post Helpful? 0

#7 Martyn.Rae   User is offline

  • The programming dinosaur
  • member icon

Reputation: 547
  • View blog
  • Posts: 1,420
  • Joined: 22-August 09

Re: dynamic array within a class

Posted 01 March 2010 - 10:48 PM

Your problem is here:

while (!voters.eof()) 
        { 
                // Read in id 
                voters >> id; 
                // Read in votes 
                voters >> votes; 
                // Initiate object of VOTER 
                VOTER v (id, votes); 
                // Store object in the vector 
                storeVoters.push_back (v); 
        }



VOTER v is creating an instance of the VOTER class on the stack. The instant you get to the end of the while loop, to go back up to the top, it is wiped from the stack. So, you are effectively adding garbage to your storeVoters array.

You will need to dynamically allocate v, using the new operator. That will sort this problem out. Don't forget to delete all VOTER instances held by the storeVoters array before your program ends.
Was This Post Helpful? 0
  • +
  • -

#8 Guest_Kae*


Reputation:

Re: dynamic array within a class

Posted 01 March 2010 - 11:05 PM

View PostMartyn.Rae, on 01 March 2010 - 09:48 PM, said:

Your problem is here:

while (!voters.eof()) 
        { 
                // Read in id 
                voters >> id; 
                // Read in votes 
                voters >> votes; 
                // Initiate object of VOTER 
                VOTER v (id, votes); 
                // Store object in the vector 
                storeVoters.push_back (v); 
        }



VOTER v is creating an instance of the VOTER class on the stack. The instant you get to the end of the while loop, to go back up to the top, it is wiped from the stack. So, you are effectively adding garbage to your storeVoters array.

You will need to dynamically allocate v, using the new operator. That will sort this problem out. Don't forget to delete all VOTER instances held by the storeVoters array before your program ends.


I don't think I'm understanding this right. The "storeVoters.push_back (v)" pushes the object into a vector. The vector stores the private string variables correctly, but loses the private array somewhere. Vectors have a new operator?

I apologize if I sound like a newb. This is only my second class, and some things I'm just not quite understanding.

Much Mahalos,
~K
Was This Post Helpful? 0

#9 jjl   User is offline

  • Engineer
  • member icon

Reputation: 1270
  • View blog
  • Posts: 4,998
  • Joined: 09-June 09

Re: dynamic array within a class

Posted 01 March 2010 - 11:12 PM

You should post your entire code so we can see the actual process,
its probably better to write the push back like this
 storeVoters.push_back (VOTES(id,votes));


Was This Post Helpful? 0
  • +
  • -

#10 Martyn.Rae   User is offline

  • The programming dinosaur
  • member icon

Reputation: 547
  • View blog
  • Posts: 1,420
  • Joined: 22-August 09

Re: dynamic array within a class

Posted 01 March 2010 - 11:15 PM

Let's look at the code:

while (!voters.eof())  
        {  
                // Read in id  
                voters >> id;  
                // Read in votes  
                voters >> votes;  
                // Initiate object of VOTER
                // >>> VOTER v is being created as an object on the stack  <<<
                // >>> It's scope is between the end of this statement     <<<
                // >>> and just before the curly brace that marks the end  <<<
                // >>> of the while loop                                   <<<
                VOTER v (id, votes);  
                // Store object in the vector  
                // Immediately after the code for the next line, the       <<<
                // variable v is removed from the stack
                storeVoters.push_back (v);  
                // The stack is cleaned up at this point, so v is referred <<<
                // to as out of scope. Effectively it no longer exists     <<<
        }



I hope that helps
Was This Post Helpful? 0
  • +
  • -

#11 jjl   User is offline

  • Engineer
  • member icon

Reputation: 1270
  • View blog
  • Posts: 4,998
  • Joined: 09-June 09

Re: dynamic array within a class

Posted 02 March 2010 - 07:53 AM

I thought vector Push_back created a copy of the reference and thrn stored that copy in the container? So even though the original is going out of scope i dont think the copy in the container is
Was This Post Helpful? 0
  • +
  • -

#12 Martyn.Rae   User is offline

  • The programming dinosaur
  • member icon

Reputation: 547
  • View blog
  • Posts: 1,420
  • Joined: 22-August 09

Re: dynamic array within a class

Posted 02 March 2010 - 07:56 AM

Whether the container takes a copy of a reference or the reference itself, one or both would refer to an object that has gone out of scope will causes the error that the poster has encountered.

Seen from the internals perspective, the reference is only a pointer the object disappears so the pointer is invalid. Only if you take an entire copy of the object does it cease to be a problem.

This post has been edited by Martyn.Rae: 02 March 2010 - 07:59 AM

Was This Post Helpful? 0
  • +
  • -

#13 jjl   User is offline

  • Engineer
  • member icon

Reputation: 1270
  • View blog
  • Posts: 4,998
  • Joined: 09-June 09

Re: dynamic array within a class

Posted 02 March 2010 - 08:43 AM

I think it accepts a reference as a param but then takes a copy of the actual object, i think u pass thr param by reference to avoid creating twp copies , i could be wrong though
Was This Post Helpful? 0
  • +
  • -

#14 jjl   User is offline

  • Engineer
  • member icon

Reputation: 1270
  • View blog
  • Posts: 4,998
  • Joined: 09-June 09

Re: dynamic array within a class

Posted 02 March 2010 - 01:04 PM

I think it accepts a reference as a param but then takes a copy of the actual object, i think u pass thr param by reference to avoid creating twp copies , i could be wrong though
Was This Post Helpful? 0
  • +
  • -

#15 Guest_Guest*


Reputation:

Re: dynamic array within a class

Posted 03 March 2010 - 10:34 AM

Hey All,

I just wanted to thank everyone for their help! My instructor gave me the hint to "use the copy constructor" since, as Martyn pointed out, the array will be deleted as it goes out of reference, leaving a hanging pointer.

Again, thanks to everyone!

~K
Was This Post Helpful? 0

Page 1 of 1