I was wondering why this size_t
is used where I can use say int type. Its said that size_t
is a return type of sizeof
operator. What does it mean? like if I use sizeof(int)
and store what its return to an int
type variable, then it also works, it's not necessary to store it in a size_t
type variable. I just clearly want to know the basic concept of using size_t
with a clearly understandable example.Thanks
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With