Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can anyone explain why size_t type is used with an example?

Tags:

c++

c

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

like image 385
N. F. Avatar asked Mar 10 '12 23:03

N. F.


2 Answers

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.

like image 86
Pubby Avatar answered Oct 20 '22 14:10

Pubby


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.

like image 36
torek Avatar answered Oct 20 '22 12:10

torek