class BigInt { private: static const int max_length = 300; int c; int number[max_length]; int to_int(char symbol) { return (symbol >= '0' && symbol <= '9') ? (int)symbol - '0' : -1; } public: BigInt(char* str) { c = strlen(str) - 1; int pos = 0; if (c > max_length) { cout << "Max length is " << max_length << "but your number has length" << c << endl; return; } for (int i = c; i <= 0; i--) { number[pos] = to_int(str[i]); pos++; } } void printNumber(void) { for (int i = c; i >= 0; i--) { cout << number[i]; } cout << "\n"; } }; 

There is a constructor that accepts a string-number, the digits of which is written into the array number. When outputting this array, I get for some reason random values.

 int main(void) { char str[]="111111111"; BigInt test(str); test.printNumber(); return 0; } 

    2 answers 2

     for(int i = c;i<=0;i--) 

    Well, i.e. while i not greater than zero, then ...

    The condition you set is incorrect.

    I would rewrite your code like this:

     class BigInt { private: static const int max_length = 300; int number[max_length]; unsigned int c; static int to_int(char symbol) { if (symbol < '0' || symbol > '9') throw exception("Wrong input"); return symbol - '0'; } public: BigInt(const char * str) { c = strlen(str); if (c > max_length) throw exception("Wrong length"); for(unsigned int i = 0; i < c; ++i) { number[i] = to_int(str[ci-1]); } } void printNumber(void) { for(int i = c-1; i >= 0; i--) { cout<<number[i]; } cout<<"\n"; } }; 

    And yet - the name c for a variable that should mean something in a class is no good. This is the name for a local loop variable, for example ... but not for the length of a number.

       c = strlen(str) - 1; 

      Why do you deduct 1? The length of it is the length, not necessary.

       for(int i = c;i>=0;i--) 

      <= Assume a typo.
      Yes, not a typo, but an error ... =)

      Something like this:

       BigInt(char * str){ c = strlen(str); int pos=0; if(c > max_length){ cout<<"Max length is "<<max_length<<"but your number has length"<<c<<endl; return; } for(int i = 0; i < c; i++){ number[pos] = to_int(str[i]); pos++; } } void printNumber(void){ for(int i = 0; i < c; i++){ cout<<number[i]<<"\n"; } cout<<"\n"; }