Home › Forums › C Programming › Array Problem
- This topic has 1 reply, 2 voices, and was last updated 14 years, 9 months ago by GWILouisaxwzkla.
- AuthorPosts
- February 21, 2010 at 3:43 am #2241FedericDeLoitteParticipant
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;
}
- February 21, 2010 at 10:09 pm #3639GWILouisaxwzklaParticipant
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 ?):
123<br />int array [ g + 1 ];<br />If you want a arbitrary length array you have to allocate it at run time , like:
123<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 )………
- AuthorPosts
- The forum ‘C Programming’ is closed to new topics and replies.