Pass object array into member function - c++

Here is the class defination:
class Unit
{
public:
Unit();
~Unit();
void set_unit(int a);
void modify_flag(Unit&);
void modify_array(Unit array[], int len); // ?? The problem
int show_unit();
private:
int ai;
};
And the implementation of the member functions:
void Unit::set_unit(int a)
{
ai = a;
}
void Unit::modify_flag(Unit& u)
{
u.set_unit(20);
}
void Unit::modify_array(Unit array[], int len) // ?? The problem
{
for (int i = 0; i < len; ++i)
{
modify_flag(array[i]);
array[i].modify_array(array, len);
}
}
int Unit::show_unit()
{
return ai;
}
And finally the main code:
int main(int argc, char const *argv[])
{
int len = 10;
Unit* array = new Unit[len];
for (int i = 0; i < len; ++i)
{
array[i].set_unit(0);
}
array[5].modify_array(array,len); // ?? The problem
for (int i = 0; i < len; ++i)
{
cout << array[i].show_unit() << endl;
}
delete [] array;
return 0;
}
I passed an array of objects into the member function of the class as the parameter, but it aborted suddenly. I have checked my code many times to make sure the counter did not accumulate over the array length. Therefore, I think there must be something wrong with the object array as the parameter, but I could not figure it out. What happened with my code ??

You have uncontrolled recursion.
In modify_array the program will call
array[i].modify_array(array, len);
len times, each of which will call
array[i].modify_array(array, len);
len times, each of which will call
array[i].modify_array(array, len);
len times, each of which will call
array[i].modify_array(array, len);
len times...
You should be able to see where this is going.
Unfortunately, I'm not sure what your goal is so a can't suggest a proper solution, but You must have some exit condition to stop the chain of calls before you run out of automatic storage (most likely stack space).
For example you could
void Unit::modify_array(Unit array[], int len) // ?? The problem
{
for (int i = 0; i < len; ++i)
{
modify_flag(array[i]);
array[i].modify_array(array, len - 1); // note the -1
}
}
so that every iteration looks at less of the array. Eventually len will be 0 and i < 0 will result in no further calls. What good this does you, I can't say, but it stops the recursion.
Do you need the recursion at all? I don't know.

Define the contructor & destructor of Unit Class.
To create array of objects : Unit *array[len].
Now you need to instantiate the objects by using new operator.
Eg. array[1] = new Unit();
As you are using an object pointer you need to use arrow (->) operator to call functions instead of dot(.) operator.
Now when you call member functions from other member function of the same class you don't need to create and object to call that method.
One more point which was mentioned earlier by some other personnel modify_arraycalls itself and it is an infinite recursion.

Thanks user4581301 for help! I finally found the mistake I made.
The code I had written was to modify the whole array with a random starting index, so I tried to do it by resursive calls. I forgot to put the terminal condition, which must be the most important part, in my recursive function.
void Unit::modify_array(Unit array[], int len)
{
for (int i = 0; i < len; ++i)
{
if(need_to_modify(array[i]))
array[i].modify_array(array, len);
}
}
Something like this to jump out the loop. This was the my practice to get familiar with the recursive function. Thanks everyone.

Related

Return char[256] from an accessor of a char[256] attribute

class A{
char info[256];
public:
char* getInfo();
A(char i[256]);
//A.cpp
#include "A.h"
char * A::getInfo(){
return(&info[256]);
}
A::A(char i[256]){
info[256]=i[256];
}
I'm struggling with the accessor. When I try to use getInfo(), I get a char*, and thus with
char test[256] = "test";
FractionException d(test);
for (int i = 0; i < 256; i++) {
cout << d.getInfo()[i] ;
}
I get
╠╠╠╠╠╠╠╠test
I guess I'm doing things the wrong way, but I cant figure it out..
By the way, VScode also warn me on
info[256]=i[256]
by telling me that 257 octets bytes might be written (C6386) but I dont get it ...
Could you help me please ? Thanks !
The problem is, your constructor is not initializing the contents of the info array correctly, and your accessor is returning a bad pointer.
In the constructor, info[256]=i[256] does not do what you think it does. You are trying to copy the 257th element of i into the 257th element of info, which is Undefined Behavior since neither array has 257 elements. That is why the compiler is warning you about it.
Try this instead:
A::A(char i[256]){
for(int x = 0; x < 256; ++x){
info[x] = i[x];
}
}
Alternatively:
#include <algorithm>
A::A(char i[256]){
std::copy_n(i, 256, info);
}
As for the accessor, it is returning a pointer to the non-existent 257th element. You need to return a pointer to the 1st element instead:
char * A::getInfo(){
return(&info[0]);
}
Or simply:
char * A::getInfo(){
return info;
}
This declaration of the constructor
A(char i[256]);
does not make a great sense because the compiler will adjust the parameter declaration like
A(char *i);
Taking into account this code snippet
char test[256] = "test";
FractionException d(test);
for (int i = 0; i < 256; i++) {
cout << d.getInfo()[i] ;
}
It seems you want that the constructor would accept a string. If so then it should be declared like
A( const char * );
and it can be defined like
#include <cstring>
//...
A::A( const char *i ){
strncpy( info, i, sizeof( info ) );
info[sizeof( info ) - 1] = '\0';
}
The member function getInfo should return the array instead of the address of the non-existent element info[256]
char * A::getInfo(){
return info;
}
This method should be also overloaded
const char * getInfo() const;
And this loop
for (int i = 0; i < 256; i++) {
cout << d.getInfo()[i] ;
}
should be substituted for this statement
std::cout << d.getInfo();

c++ int member changes on its own

I am new to c++.
It looks like member variable _scheduleSize gets value kind of "integer_half_max" without any reason. Could someone please explain me why is this happening?
Invocation
leds.addSchedulePoint(new ScheduledLedPoint(ScheduleTime(9), 0));
of method:
void ScheduledLeds::addSchedulePoint(ScheduledLedPoint *schedulePoint) {
Serial.print("_scheduleSize:");
Serial.println(_scheduleSize);
_schedule[_scheduleSize++] = schedulePoint;
Serial.print("_scheduleSize:");
Serial.println(_scheduleSize);
for (size_t i = 0; i < _scheduleSize; i++) {
Serial.println(_schedule[i]->getLevel());
}
}
results in such console output :
_scheduleSize:0
_scheduleSize:1073680860
0
Exception (28):
epc1=0x40206514 epc2=0x00000000 epc3=0x00000000 excvaddr=0x00000010 depc=0x00000000
Below you can see entire class:
class ScheduledLeds {
public:
ScheduledLeds(int pin);
void addSchedulePoint(ScheduledLedPoint *schedulePoint);
void process(ScheduleTime currentTime);
void freezeLedLevel(int targetLevel, int minutes);
int _pin;
private:
ScheduledLedPoint *_schedule[];
int _scheduleSize;
int _count;
int _size;
long _unfreezeTime;
int _lastLevel;
ScheduleTime _lastTime;
void setTransitionalLightLevel(ScheduleTime now, ScheduledLedPoint nextPoint);
void setLightLevel(int targetLevel);
};
ScheduledLeds::ScheduledLeds(int pin) {
pinMode(pin, OUTPUT);
_pin = pin;
_scheduleSize = 0;
_size = 10;
_unfreezeTime = millis();
ScheduledLedPoint *_schedule[_size];
}
void ScheduledLeds::addSchedulePoint(ScheduledLedPoint *schedulePoint) {
Serial.print("_scheduleSize:");
Serial.println(_scheduleSize);
_schedule[_scheduleSize++] = schedulePoint;
Serial.print("_scheduleSize:");
Serial.println(_scheduleSize);
for (size_t i = 0; i < _scheduleSize; i++) {
Serial.println(_schedule[i]->getLevel());
}
}
ScheduledLedPoint *_schedule[]; is not valid C++ and shouldn't compile. Some compilers accept it as an extension - but even there, it's an array of zero size; _schedule[x] exhibits undefined behavior for any value of x.
When you write ScheduledLedPoint *_schedule[_size] in the constructor, that doesn't affect the data member named _schedule, as you seem to believe. Instead, it creates and immediately destroys a local variable that also happens to be named _schedule; this has exactly zero net effect.
For an array-like data structure of variable size, use std::vector.
because you have syntax error including this recursive function

Array elements of a class object are not being set correctly, set() and get() member functions likely cause

This is my first time working with classes in C++ and I seem to be getting tripped up quite a lot. My program is supposed to be a rewrite of a previous program that used struct (see here: Random number generator in a for loop gives same numbers each time), but using a class instead.
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
using namespace std;
const int WHEEL_POSITIONS = 30;
const char wheelSymbols[WHEEL_POSITIONS + 1] = "-X-X-X-X-X=X=X=X*X*X*X*X#X#X7X";
class slotMachine
{
private:
int spinPos;
char spinSymbol;
public:
slotMachine(); // Constructor
char symbols[WHEEL_POSITIONS + 1]; // Should be private?
void setSpinSymbol(); // Spins the wheels
char getSpinSymbol() const // Returns the symbol
{ return spinSymbol; }
} wheels[3];
// Constructor initializes slot wheels to contents of wheelSymbols
slotMachine::slotMachine()
{
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < (WHEEL_POSITIONS + 1); j++)
{
wheels[i].symbols[j] = wheelSymbols[j];
}
}
}
void slotMachine::setSpinSymbol()
{
for (int i = 0; i < 3; i++)
{
wheels[i].spinPos = (rand() % WHEEL_POSITIONS);
wheels[i].spinSymbol = wheels[i].symbols[(wheels[i].spinPos)];
}
}
void displayResults(slotMachine fwheels[3])
{
for (int i = 0; i < 3; i++)
{
cout << fwheels[i].getSpinSymbol();
}
}
void displayResults(slotMachine []);
//bool getWinner(slotMachine []);
int main(void)
{
slotMachine wheels[3];
time_t seed;
time(&seed);
srand(seed);
displayResults(wheels);
return 0;
}
The code compiles but outputs the following:
I have a feeling this error is caused by something having gone amiss in my constructor slotMachine, my getSpinSymbol() function, or my setSpinSymbol() function, but I've looked it over several times and can't seem to figure it out. I've read a handful of material online covering classes in C++, but I'm still very new and very shaky on the concept--apologies if it's something small or obvious that I've overlooked.
There are several issues with your code:
1.Class names should be started with upper case letter. slotMachine -> SlotMachine
2.Remove wheels[3] after class definition.You are using the array declared in main() method.
3.Why you are declaring displayResults(..) again after it's definition?
4.You are not calling setSpinSymbol() before displayResults(..).
The problem was explained to me by a friend not on StackOverflow, and I will transcribe his answer here in case anyone else (for any reason) runs into the same problem:
You aren't using constructors and methods correctly. You shouldn't be
accessing wheels (the array of slotMachine objects) directly inside
those methods; you should just be performing operations on "this," the
slotMachine object on which the method was called. For example, the
constructor slotMachine::slotMachine() is automatically called for
each element of the array wheels. You just need to initialize the
current slotMachine object inside the constructor:
slotMachine::slotMachine()
{
for (int j = 0; j < (WHEEL_POSITIONS + 1); j++)
{
this->symbols[j] = wheelSymbols[j];
}
}
And slotMachine::setSpinSymbol() should just set the value of
spinSymbol for the object on which the method was called:
void slotMachine::setSpinSymbol()
{
this->spinPos = (rand() % WHEEL_POSITIONS);
this->spinSymbol = symbols[this->spinPos];
}
(In all of this code, the this-> part is actually unnecessary; you
can leave it out if you want. I put it in to try to make it clearer
that these methods are operating on fields of "the current object.")
Now, the reason you are getting garbage is because you never call
setSpinSymbol(), so the spinSymbol field is never initialized in
these objects. You probably want to call setSpinSymbol() in the
constructor, so that the spinSymbol field is guaranteed to be
initialized.
This explanation did solve my problem, and my program now outputs the correct information, so I believe it to be correct. My issues with using constructors and methods correctly has been explained here, and the reason why I was getting garbage values (as well as a few other points) was answered by another commenter.

cannot convert from 'std::string' to 'char'

Changed completely due to suggestions from other member. Most problems solved, still having problems. Now won't output any names from the array in main. Not sure if I'm passing them back correctly from function.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void bubblesort(string[], const int);
int sub = 0;
int main()
{
const int maxsize = 100;
string friendArray[maxsize];
ifstream friends;
friends.open("myFriends.dat");
while (sub < maxsize)
{
getline(friends, friendArray[sub]);
sub++;
}
bubblesort(friendArray, maxsize);
cout<<friendArray[0]<<" "<<friendArray[1]<<" "<<friendArray[2];
system("pause");
return 0;
}
void bubblesort(string *array, const int size)
{
bool swap;
string temp;
do
{
swap = false;
for (int count = 1; count < (size - 1); count++)
{
if(array[count-1] >array[count])
{
temp = array[count-1];
array[count-1] = array[count];
array[count] = temp;
swap = true;
}
}
}
while(swap);
}
Your problem isn't necessarily that temp inside bubblesort is not a char, the problem is that array is declared as a string and not a string[].
The reason you're getting the error is because array[count+1] is of type char, and temp is of type string. std::swap expects two elements of the same type.
However, that may be the least of your problems, your code doesn't compile for quite a few reasons. Not just that but you're passing in maxsize to bubblesort at each iteration. There's a flaw in both your logic and your syntax.
EDIT: Since you're still having trouble getting the sorting to work, here's a working modification of your code:
#include <iostream>
void bubblesort(std::string array[], size_t size)
{
bool bSwapped;
std::string temp;
do
{
bSwapped = false;
for (size_t count = 1; count < size; count++)
{
if(array[count-1] > array[count])
{
std::swap(array[count-1], array[count]);
bSwapped = true;
}
}
}
while(bSwapped);
}
int main(void)
{
std::string array[] = { "def", "ghk", "abc", "world", "hello" };
bubblesort(array, sizeof(array)/sizeof(*array));
for (size_t i = 0; i < sizeof(array)/sizeof(*array); ++i)
std::cout << array[i] + " ";
std::cout << std::endl;
return 0;
}
bubblesort could also be written as: void bubblesort(std::string *array, size_t size). There's no difference in this case since, when passed to a function, arrays decay into pointers.
Since arrays are passed by reference, a pointer to the first element, any modifications made to array inside of bubblesort will actually be modifying your array in main. So that's how arrays are "returned".
std::vector is a good alternative to the standard array, since it automatically resizes and obviously contains the length of the internal array so that you don't have to pass the size everywhere you pass an std::vector. You can also use it the same way as a regular array.
temp is a string, array[count] is a char (since an std::string is a vector of char elements.) I'm not sure what you're trying to do here, but the compiler is correct - you can't assign a char to a string.
You could change temp to be a char, since all you do with it is assign a char to it, and then assign it back to an element of array, which is also a char.
You need to declare temp as char. You can use std::swap to avoid such mistakes in the future:
std::swap(array[count], array[count+1]);
This would make your code compile, but it would not do what you're trying to do (bubblesort). The problem is that you are passing a single string (which is also an "array" of characters) instead of an array of strings, which is, in a very lose sense, "an array of arrays of characters". Your bubblesort needs to accept string *array as its first parameter.

Deallocation of an array of objects?

I'm having some issues deallocating arrays of a class I have. Below is the Class, a simplified implementation and my code I have tried to use to close it.
Characters class
#include <cstdlib>
class Character
{
private:
bool human;
int Xposition; // the character's postion on the board.
int Yposition; // the character's postion on the board.
bool alive;
public:
Character(); //This is my constructor
~Character(); //This is my destructor
bool isHuman(); //return whether type 1 aka Human
bool isZombie(); //return whether type 2 aka Zombie
void setHuman(); //set to type 1 or Human
void setZombie(); //set to type 2 or Zombie
void setPos(int xpos, int ypos); //set the board position
int X();
int Y();
bool isAlive(); //checks to see if a Human is still alive and to be displayed
bool Dead(); //kills the character and sets alive to false
int num_moves_allowed; //number of moves allowed.
};
Allocation code:
Character *characters[11];
int human_count = 0;
for(int i=0; i<12; i++)
{
characters[human_count] = new Character();
human_count++;
}
Termination code:
for(i=11;i<=0;i--)
{
if(characters)
{
characters[i]->~Character();
delete characters[i]; characters[i] = NULL;
}
}
if(characters)
{
//ERROR IS HERE
delete [] characters;
}
I have tried a number of different "delete" commands on the array and I keep getting an "Debug Assertion Failed!" window. It says that the dbgdel.cpp from visual studio vctools is the problem place on Line 52.
It also says "Expression: _BLOCK_TYPE_IS_VALID(pHead->nBlockUse)
Someone please help me I'm sure this is very simple.
I'd suggest you avoid using arrays all together. Use a vector of characters.
Declare your vector as
vector<Character> vCharacters;
then insert objects as
for(int i = 0; i < 100; i++)
vCharacters.push_back(Character());
If you want to store pointers to Character objects then wrap them in a shared_ptr which will take care of deallocating them for you.
vector<shared_ptr<Character>> vCharacters;
for(int i =0; i < 100; i++)
{
shared_ptr<Character> spCharacter(new Character());
vCharacters.push_back(spCharacter);
}
Avoid managing memory yourself when C++ can do it fo ryou
The characters array was allocated on the stack, so you don't have to delete it. However, if you want the array to survive the local scope, create it with something like this:
Character **characters = new Character[11];
then your delete[] line should work fine.
Also note that you don't need to call the destructor of Character explicitly: it is called automatically by delete.
As obelix mentioned, you should use a vector from the Standard Template Library.
However, if you're determined to use a raw array:
const int MAX_CHARACTERS = 11;
Character *characters[MAX_CHARACTERS];
for(int characterCount = 0; characterCount < MAX_CHARACTERS; ++characterCount)
{
characters[characterCount] = new Character();
}
...
if (characters != NULL)
{
for(int i = 0; i < MAX_CHARACTERS; ++i)
{
delete characters[i];
}
}
Paolo Capriotti is correct that characters should be declared with new if you want it to last beyond its scope:
const int MAX_CHARACTERS = 11;
Character **characters = new Character*[MAX_CHARACTERS];
for(int characterCount = 0; characterCount < MAX_CHARACTERS; ++characterCount)
{
characters[characterCount] = new Character();
}
...
if (characters != NULL)
{
for(int i = 0; i < MAX_CHARACTERS; ++i)
{
delete characters[i];
}
delete [] characters;
}
A better solution is the standard vector class:
#include <vector>
...
const int MAX_CHARACTERS = 11;
std::vector<Character> characters;
for (int i = 0; i < MAX_CHARACTERS; ++i)
{
characters.push_back(Character());
}
...
characters.clear();
Notice how much easier the cleanup was? (And in this case, it's optional, since when characters is destroyed it will automatically call the destructor of each item it contains.)
Also:
Character *characters[11];
should be
Character *characters[12];
and
for(i=11;i<=0;i--)
should be
for(i=11;i>=0;i--)
i realize this is a simplified use and all, but why bother with heap access at all?
just using
Character characters[11];
could be just as valid, and safe.
std::vector<> is nice, but if the list is always fixed size, and there's no heap involved in member data, why not?