On systems where a char is represented using 8 bits,
If sizeof(size_t)
is 2, then, the maximum value is: 65535
If sizeof(size_t)
is 4, then, the maximum value is: 4294967295
If sizeof(size_t)
is 8, then, the maximum value is: 18446744073709551615
If sizeof(size_t)
is 16, then, the maximum value is: 3.4028237e+38
You can use that information to extract maximum size of the string using the pre-processor.
Sample program:
#include <stdio.h>
#ifdef MAX_STRING_SIZE
#undef MAX_STRING_SIZE
#endif
// MAX_STRING_SIZE is 6 when sizeof(size_t) is 2
// MAX_STRING_SIZE is 11 when sizeof(size_t) is 4
// MAX_STRING_SIZE is 21 when sizeof(size_t) is 8
// MAX_STRING_SIZE is 40 when sizeof(size_t) is 16
// MAX_STRING_SIZE is -1 for all else. It will be an error to use it
// as the size of an array.
#define MAX_STRING_SIZE (sizeof(size_t) == 2 ? 6 : sizeof(size_t) == 4 ? 11 : sizeof(size_t) == 8 ? 21 : sizeof(size_t) == 16 ? 40 : -1)
int main()
{
char str[MAX_STRING_SIZE];
size_t a = 0xFFFFFFFF;
sprintf(str, "%zu", a);
printf("%s\n", str);
a = 0xFFFFFFFFFFFFFFFF;
sprintf(str, "%zu", a);
printf("%s\n", str);
}
Output:
4294967295
18446744073709551615
It will be easy to adapt it to systems where a char is represented using 16 bits.