So, long story short: I started using "devkitPro", which is a C++ library, however I never coded with C++ before, but I did with C#, which is pretty similar to, so I started learning a little about C++, tried to code a prototype button class, created a boolean method that would return true if the clicked area was colliding with it, then I recieved this error when I tried to compile the code I wrote.
So as normally, I did what every person would do after seeing a error: I google it. Apparentaly this error is caused because of syntax mistake. So far, so good, had dealt with it before, not too much of a problem. However, the problem is that the error points to a goddamn "}", that if I remove will cause another error because the "}" is required to end a method. I tried and tried many different ways to solve this but I simply can't find the problem. Here is the script with the problem (error points to line 20)
#include <nds.h>
#include <nds/arm9/video.h>
#include <nds/arm9/sprite.h>
#include <stdio.h>
#include <string>
using namespace std;
class Button{
public:
string name;
uint posX;
uint posY;
uint sizX;
uint sizY;
bool show;
bool pressed(uint touchX, uint touchY)
{
return (show == true && posX + sizX > touchX && posY + sizY > touchY && posX < touchX + 1 && posY < touchY + 1);
} //the error message points to this line
}
Or more expecificaly this part of the code
bool pressed(uint touchX, uint touchY)
{
return (show == true && posX + sizX > touchX && posY + sizY > touchY && posX < touchX + 1 && posY < touchY + 1);
} //the error points to this line
So uh... anyone have any idea of what is wrong here. Thanks. I don't know much about C++ and all I know is because is similar to C#.
(Unrelated but, what is so special about the string variable type that it needs its own namespace to work propely?)
I tried to code a boolean method that returns true or false depending if your mouse cursor is colling with it, but I couldn't exactly see if it works or not because of an error I don't understand what exactly is causing.
Related
I'm debugging a function that does some math with the Eigen library and am getting different results on different platforms. I don't see anything obviously wrong but I'm really not that familiar with the library. I've pulled the local variables out into a simple test application. hitRight ends up true on Mac and Windows but not on Linux. While debugging I figured out that putting .eval() at the end of the "auto rightDistance" line resolves the problem but I'd really like to understand why.
#include <stdio.h>
#include "eigen/Eigen/Core"
using namespace Eigen;
int main()
{
Vector2i p = Vector2i(302,12);
int mTabControlWidth = 20;
Vector2i mPos = Vector2i(0,0);
Vector2i mSize = Vector2i(310,24);
auto rightDistance = (p - (mPos + Vector2i(mSize.x() - mTabControlWidth, 0))).array();
bool hitRight = (rightDistance >= 0).all()
&& (rightDistance < Vector2i(mTabControlWidth, mSize.y()).array()).all();
if (hitRight)
printf("Hit Right\n");
printf("Hit none\n");
return 0;
}
Vector2i(mSize.x() - mTabControlWidth, 0) gets destructed at the next ;, while rightDistance still refers to it. That is undefined behavior, i.e., with some luck it works like you expect, but it might do whatever the compiler wants to do (most likely crash or return arbitrary results).
As Avi said, just avoid the auto. In your case, you should also use Array2i instead of Vector2i. This saves you from writing all the .array().
Also, if the auto expression worked, rightDistance would be evaluated twice instead of once (o.t.o.h, compiler are usually good at optimizing that away).
int main()
{
Array2i p(302,12);
int mTabControlWidth = 20;
Array2i mPos(0,0);
Array2i mSize(310,24);
Array2i rightDistance = (p - (mPos + Array2i(mSize.x() - mTabControlWidth, 0)));
bool hitRight = (rightDistance >= 0).all() && (rightDistance < Array2i(mTabControlWidth, mSize.y())).all();
if (hitRight)
printf("Hit Right\n");
printf("Hit none\n");
return 0;
}
Here is the chunk of code in question that I've pulled from my program:
#include <vector>
using namespace std;
vector<double> permittingConstructionCosts(56);
static const int PERMITTING_PERIODS = 0;
static const int CONSTRUCTION_PERIODS = 11;
static const double CONSTRUCTION_COSTS = 2169506;
static const double PERMITTING_COSTS = 142085;
static const int PERMITTING_CONSTRUCTION_PERIODS = PERMITTING_PERIODS + CONSTRUCTION_PERIODS;
void calcExpenses // Calculates permitting and construction expenses
(
vector<double>& expense,
double value1,
double value2
)
{
int i;
for (i=0; i<=PERMITTING_PERIODS + 1; i++)
{
expense[i] = value1;
}
for (i=PERMITTING_PERIODS + 2; i<expense.size(); i++)
{
if (i < PERMITTING_CONSTRUCTION_PERIODS + 2)
{
expense[i] = value2;
}
}
}
int main()
{
if (PERMITTING_PERIODS != 0)
{
calcExpenses(permittingConstructionCosts, -PERMITTING_COSTS/PERMITTING_PERIODS, -CONSTRUCTION_COSTS/CONSTRUCTION_PERIODS);
}
else
{
calcExpenses(permittingConstructionCosts, 0, -CONSTRUCTION_COSTS/CONSTRUCTION_PERIODS);
}
return 0;
}
According to ideone (http://ideone.com/LpzUny) the code has a runtime error that returns "time: 0 memory: 3456 signal:11".
I've tried to look for solutions on SO and found the following links:
How can I avoid a warning about division-by-zero in this template code?
How to eliminate "divide by 0" error in template code
However, I don't know how to use templates because I am new to c++ and I'm not sure I need to use them in this case so I have no clue how to adapt those solutions to my particular problem if it's even possible.
I'm pretty sure that the "-PERMITTING_COSTS/PERMITTING_PERIODS" is causing the problem but I thought that simply checking the divisor would solve the problem. This function seems to work for every other value other than 0 but I need to account for the case where PERMITTING_PERIODS = 0 somehow.
I would very much appreciate any help I can get. Thanks in advance!
Edit: I actually do initialize the vector in my program but I forgot to put that in because the size is decided elsewhere in the program. The chunk of code works once I fix that part by putting in a number but my program still has a runtime error when I set PERMITTING_PERIODS to 0 so I guess I have to go bug hunting elsewhere. Thanks for the help!
The problem lies inside the function, which is called by the else statement in the main function:
for (i=0; i<=PERMITTING_PERIODS + 1; i++)
{
expense[i] = value1;
}
Here, PERMITTING_PERIODS is 0, thus you loop from 0 to 2 (inclusive).
However, expense.size() is 0, since your vector is empty. As a result, you are trying to access an empty vector, which causes a segmentation fault.
With that said, print the value of i inside the loop, you should see that you try to access expense[0], but the vector is empty, so it has no first slot (basically it doesn't have any)!!
So replace that with:
expense.push_back(value1);
which will allocate enough space for your values to be pushed into the vector.
The answer given in the cited links, (i.e. "How to eliminate "divide by 0" error in template code") applies equally well here. The other answers were given in the context of templates, but this is completely irrelevant. The sample principle applies equally well with non-template code, too. The key principle is to compute a division, but if the denominator is zero, you want to compute the value of zero instead of the division.
So we want to compute -PERMITTING_COSTS/PERMITTING_PERIODS, but use the value of 0 instead of the division when PERMITTING_PERIODS is 0. Fine:
int main()
{
calcExpenses(permittingConstructionCosts,
(PERMITTING_PERIODS == 0 ? 0: -PERMITTING_COSTS)/
(PERMITTING_PERIODS == 0 ? 1: PERMITTING_PERIODS),
-CONSTRUCTION_COSTS/CONSTRUCTION_PERIODS);
return 0;
}
I'm looking into translating some code from C++ to Objective C and I ran into an instance that contains a function with a const notation at the end. I'm quite rusty on C++ and I don't remember what this would represent (I have been googling though). I'd like to know how to force this over to Objective-C. Currently, here's what I have:
C++ code:
float RenderingEngine1::RotationDirection() const
{
float delta = m_desiredAngle - m_currentAngle;
if (delta == 0)
return 0;
bool counterclockwise = ((delta > 0 && delta <= 180) || (delta < -180));
return counterclockwise ? +1 : -1;
}
Objective-C:
-(float)getRotationDirection{
float delta = desiredAngle - currentAngle;
if (delta == 0) {
return 0;
}
bool counterclockwise = ((delta > 0 && delta <= 180) || (delta < -180));
float test = counterclockwise ? +1 : -1;
NSLog(#"%f",test );
return counterclockwise ? +1 : -1; //problem
}
Edit: found the error of my ways and it was just an addition problem somewhere else in the program ('I love the easy ones'). That being said, I do want to ensure that the const declaration will not interfere with any further issues and want to check to ensure whether or not there should be any declarations I need to make (such as singleton methods and such). Thank you guys for the answers!
const in c++ means that this method doesn't alter the state of the object, thus it may use just const methods, and it can't alter class variables unless they're declared mutable.
If your class is immutable, you can safely assume that every method you've declared is the equivalent of a const method.
However, since you aren't altering any ivar, you're "translating" the code properly (logically speaking), as you aren't mutating any ivar.
I don't see any particular problem with your code, there shouldn't be a syntax (neither semantic) error.
PS: That's not how you should compare floating point numbers, look here.
I have this function to solve a maze in C++, but when I run the program I get a Bad Access Error in the recursion. I think in may be an infinite loop. I have no idea where and what is going wrong.
bool Solve_Maze(int coorx,int coory) {
if((Map[coorx][coory]==Start)||(Map[coorx][coory]==path)) {
Map[coorx][coory]=wall;
Solve_Maze(coorx+1,coory);
Solve_Maze(coorx-1,coory);
Solve_Maze(coorx,coory+1);
Solve_Maze(coorx,coory-1);
}else if(Map[coorx][coory]==End) {
cout<<"You Solved the Maze!"<<endl;
delete Map;
return(true);
}
}
1) You are not returning any value in if statement
2) Map[coorx][coory] always assigned to wall in all function call..Does wall refers to a global state?
I changed the function to return void since the value wasn't properly being returned up the stack. In this case you will just use the global found variable to check if the end was found. (this will require you to set 'found = false' every time before you run the function).
bool found = false;
You also want to do some input validation
if( coorx > maxX || coorx < 0 || coory > maxY || coory < 0) return;
You will need to replace maxX and maxY with 1 more than your maximum values for coorx and coory. That will ensure you don't get a bad access error.
bool found = false; // this will be global scope or pass it by reference
Solve_Maze(x,y);
// if(found) - found will be true if you found the end
void Solve_Maze(int coorx,int coory) {
if( coorx > maxX || coorx < 0 || coory > maxY || coory < 0) return;
else if(((Map[coorx][coory]==Start)||(Map[coorx][coory]==path))) {
Map[coorx][coory]=wall;
Solve_Maze(coorx+1,coory);
Solve_Maze(coorx-1,coory);
Solve_Maze(coorx,coory+1);
Solve_Maze(coorx,coory-1);
}else if(Map[coorx][coory]==End) {
cout<<"You Solved the Maze!"<<endl;
delete Map;
found = true;
}
}
Run it in a debugger (gdb or dbx). Compile with the -g flag so your program can be debugged. If you don't know how to use a debugger, google "dbx cheatsheet." You can isolate where it's stuck in the loop (if your guess is right) and step your way through. The total time it will take you to become proficient enough in a debugger to do this is, and to actually do it, is less than the amount of time you have spent thinking about it already.
No sarcasm is intended - people really do often overestimate the work in learning a debugger, so I want to really assert the point that it's worth it even for a simple problem, and tremendously pays off for big problems.
Valgrind detects an invalid read error I don't know how to fix or to be more precise: I don't know what the problem is.
Invalid read of size 8
at 0x443212: std::vector<Tile*, std::allocator<Tile*> >::end() const
by 0x44296C: Collection<Tile*>::Iterator::operator++()
The Iterator class is very simple (and actually a somewhat bad piece of programming) but sufficient for my needs right now. I think there are three methods you should know to hopefully help find my problem:
Iterator(size_t x, size_t y, const TileCollection& tiles)
: mTiles(&tiles)
, mX(mTiles->begin())
, mY(mTiles->at(x).begin())
{
std::advance(mX, x);
std::advance(mY, y);
bool foundFirst = false;
while (!foundFirst)
{
while (mY != mX->end() && *mY == 0) ++mY;
if (mY != mX->end()) foundFirst = true;
else
{
++mX;
if (mX != mTiles->end()) mY = mX->begin();
}
}
}
Iterator Iterator::operator++()
{
bool foundNext = false;
++mY;
while (!foundNext)
{
while (mY != mX->end() && *mY == 0) ++mY;
if (mY != mX->end()) foundNext = true;
else
{
++mX;
if (mX != mTiles->end()) mY = mX->begin();
}
}
return *this;
}
void TileCollection::add(Tile* tile)
{
Point2D p(tile->getPosition());
std::vector<Tile*> tmp(1, (Tile*)0);
if ((size_t)p.x >= mTiles.size())
mTiles.resize(p.x + 1, tmp);
if ((size_t)p.y >= mTiles.at(p.x).size())
mTiles.at(p.x).resize(p.y + 1, (Tile*)0);
mTiles.at(p.x).at(p.y) = tile;
++mNumTiles;
}
The actual code that is causing the valgrind error is the line:
while (mY != mX->end() && *mY == 0) ++mY;
...of the Iterator::operator++ method.
It looks to me that, at the least, the following line in operator++
if (mX != mTiles->end()) mY = mX->begin();
is lacking a suitable else-clause.
Consider what happens when mX actually reaches mTiles->end(): You will enter a new iteration of the outer while loop; the first line in that loop (the line that causes the Valgrind error) will evaluate mX->end() and thus attempt to dereference mX -- but mX is mTiles->end(), and it's not correct to dereference the end iterator of a collection since it doesn't actually reference an element of the collection. It looks to me as if this may be the cause of your Valgrind error.
(Note that the constructor contains essentially the same code.)
More generally, I think you need to think about how you handle reaching the end of your two-dimensional array. How does the client of your Iterator check whether it has reached the end of the iteration? How do you expect your operator++ to handle the case when it reaches the end of the two-dimensional array? Should it protect itself against getting called too often?
You can try to split up the statement in order get find out where the error occurs:
while (mY != mX->end()) // maybe here
{
if (*mY != 0) // maybe here
{
break;
}
++mY; // maybe here
}
Compiling with GCC compiler option -fno-inline helps to get a nicer stack-trace, which can help you to trace the error. It will also make your program very slow, so don't forget to remove it later.