I would like to create a variable that could store an integer of a variable size, the variable should be able to resize itself as needed.
dyn_int num = 42;
// sizeof(num) == sizeof(char)
num = 1000;
// sizeof(num) == sizeof(short)
num = 99999;
// sizeof(num) == sizeof(int)
num = 9999999999;
// sizeof(num) == sizeof(long)
Note that I'm perfectly fine with having to use functions everywhere like that:
dyn_int num = init_dyn_int(42);
// sizeof(num) == sizeof(char)
num = new_dyn_int(&num, 1000);
Note also that I'm perfectly fine with for example sizeof(num)
being a bit bigger than sizeof(char)
(to store some metadata for example).
CodePudding user response:
No, there is no such thing in C.
The closest you can get, is to have a pointer to an array of digits, and then if you run out of digits you can allocate a new array with more digits. This is what libraries like GMP do.
But the pointer is 8 bytes big, so if your numbers all fit in 8 bytes, you might as well just use 8-byte numbers directly.