Array Problem

Home Forums C Programming Array Problem

This topic contains 1 reply, has 2 voices, and was last updated by  GWILouisaxwzkla 9 years, 9 months ago.

  • Author
    Posts
  • #2241

    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;

    }

  • #3639

    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 ?):

    If you want a arbitrary length array you have to allocate it at run time , like:

    make sure to check allocation of this statement and delete the memory when your done with it ( by the end of the function call )………

You must be logged in to reply to this topic.

Share
Tweet
Share
Pin