dynamic allocation c++

#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();
}

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
If you are using an array of characters, then a simple replacement is a std::string.
For other types (including characters), use a vector.

char num[50];
becomes
std::vector<char> num(50);
> dynamically allocate the memory so i wouldn't have a fixed number like this num[50]

Use std::vector<> https://cal-linux.com/tutorials/vectors.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <iostream>
#include <vector>

struct mint
{
    mint() = default ;

    explicit mint( const char* cstr )
    {
        if(cstr) for( const char* p = cstr ; *p != 0 ; ++p )
        {
            if( std::isdigit(*p) ) digits.push_back( *p - '0' ) ;
            else throw std::domain_error( "invalid decimal digit" ) ;
        }
    }

    std::ostream& display( std::ostream& stm = std::cout ) const // display, arguably improved
    {
        if( digits.empty() ) return stm << '0' ;
        for( int d : digits ) stm << d ;
        return stm ;
    }

    private: std::vector<int> digits ; // https://cal-linux.com/tutorials/vectors.html
};

// an overloaded stream insertion operator (which calls display) would be convenient.
std::ostream& operator<< ( std::ostream& stm, const mint& m ) { return m.display(stm) ; }

int main()
{
    const mint number( "12345678908765432101234567890" ) ;
    std::cout << "number: " << number << '\n' ;
}

http://coliru.stacked-crooked.com/a/4300204642ff4a62
By the way, Mint::Mint(int n) uses i before it is initialized.
Topic archived. No new replies allowed.