- This topic has 1 reply, 2 voices, and was last updated 14 years, 10 months ago by .
Viewing 1 reply thread
Viewing 1 reply thread
- The forum ‘C Programming’ is closed to new topics and replies.
Home › Forums › C Programming › Array Problem
I made a function containing an array that is declared as so: factor[ g + 1] and when the computer runs it, results in this: factor[-1]. Why?
Heres my source code:
bool PerfectCalculator(int g)
{
bool x;
int i, factor[g + 1], sum;
x = false;
sum = 0;
for (i=2; i
if (g % i == 0) {
factor = i;
}
else {
factor = 0;
}
}
for (i=0; i
sum += factor;
}
if (sum == g) {
x = true;
}
else {
x = false;
}
return x;
}
Unless theres a new C++ standard , you cannot declare arrays of an arbitrary length ( the length must be declared as a constant so the compiler knows how to set up the function’s stack frame at compile time ). So you can’t do this ( I’m suprised this compiled, what compiler are you using ?):
1 2 3 | <br /> int array [ g + 1 ];<br /> |
If you want a arbitrary length array you have to allocate it at run time , like:
1 2 3 | <br /> int * array = new int [ g + 1 ];<br /> |
make sure to check allocation of this statement and delete the memory when your done with it ( by the end of the function call )………