can anyone explain why size_t type is used with an example?
size_t
is guaranteed to be able to represent the largest size possible, int
is not. This means size_t
is more portable.
For instance, what if int
could only store up to 255 but you could allocate arrays of 5000 bytes? Clearly this wouldn't work, however with size_t
it will.
The simplest example is pretty dated: on an old 16-bit-int
system with 64 k of RAM, the value of an int
can be anywhere from -32768 to +32767, but after:
char buf[40960];
the buffer buf
occupies 40 kbytes, so sizeof buf
is too big to fit in an int
, and it needs an unsigned int
.
The same thing can happen today if you use 32-bit int
but allow programs to access more than 4 GB of RAM at a time, as is the case on what are called "I32LP64" models (32 bit int
, 64-bit long
and pointer). Here the type size_t
will have the same range as unsigned long
.