hello everyone i just started my implementation of a bigint class and i got stuck is there a way for me to dynamically allocate the memory so i wouldn't have a fixed number like this num[50] and is there a better way the imrove my display method thank you in advance

#include <iostream>
#include <string>
using namespace std;

class Mint {
public:

    Mint();
    Mint(int);
    Mint (const char* s);
    void display();
private:
    char  num[50];
};



Mint::Mint()
{
    num[0] = 0;
}
Mint::Mint(int n)
{
    int i;
    while(n>0)
    {
        num[i] = n%10;
        n = n/10;
        i++;
    }
}
Mint::Mint(const char* s)
{
        int i = 0 ;
        while(s[i] != '\0')
                {
                    i++;
                }
                i--;
                while(i>=0){
                    num[i] = s[i] - '0';
                    i--;
                }
}
void Mint::display(){
    int i;
    for(i=0;i<=strlen(num);i++)
    {
        cout << char('0'+num[i]);
    }
}

#include "Mint.h"
#include <iostream>
#include <string>
using namespace std;



int main()
{
    Mint x,z;
    Mint a = "0655478461469974272005572";
    Mint b = 12536458;

    a.display();
}

Using a string as the collection holding the digits will automatically reallocate memory and make the display() function much simpler, while providing you with an indexed collection that you can iterate through.

There are a number of solutions to this problem. You can use a std::vector for the array which will happily resize itself as needed. Much better than "rolling your own", which I have done in the past before the STL was available. For automatically resizable arrays these days I use vectors. Simple, and they take care of the care and feeding of the array.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.