Alex Vinokur said:
Why was the size_t type defined in compilers in addition to unsigned
int/long?
Because size_t has a different purpose to unsigned int and unsigned long.
Its primary purpose is to be able to contain a value equal to the size of
any object, although it can certainly be used for other things.
When/why should one use size_t?
When one is storing either the size of an object, or a count of objects. To
illustrate this, just look at some of the standard library functions that
use size_t:
int setvbuf(FILE *stream, char *buf, int mode, size_t size);
size_t fread(void *ptr, size_t size, size_t nmemb,
FILE *stream);
size_t fwrite(const void *ptr, size_t size, size_t nmemb,
FILE *stream);
void *calloc(size_t nmemb, size_t size);
void *malloc(size_t size);
void *realloc(void *ptr, size_t size);
void *bsearch(const void *key, const void *base,
size_t nmemb, size_t size,
int (*compar)(const void *, const void *));
void qsort(void *base, size_t nmemb, size_t size,
int (*compar)(const void *, const void *));
int mblen(const char *s, size_t n);
int mbtowc(wchar_t *pwc, const char *s, size_t n);
size_t mbstowcs(wchar_t *pwcs, const char *s, size_t n);
size_t wcstombs(char *s, const wchar_t *pwcs, size_t n);
void *memcpy(void *s1, const void *s2, size_t n);
void *memmove(void *s1, const void *s2, size_t n);
char *strncpy(char *s1, const char *s2, size_t n);
char *strncat(char *s1, const char *s2, size_t n);
int memcmp(const void *s1, const void *s2, size_t n);
int strncmp(const char *s1, const char *s2, size_t n);
size_t strxfrm(char *s1, const char *s2, size_t n);
void *memchr(const void *s, int c, size_t n);
size_t strcspn(const char *s1, const char *s2);
size_t strspn(const char *s1, const char *s2);
void *memset(void *s, int c, size_t n);
size_t strlen(const char *s);
size_t strftime(char *s, size_t maxsize,
const char *format, const struct tm *timeptr);