What is size_t in C?

Question: What is Type size_t in C?

Answer: Type of ‘size_t’ is what type sizeof operator returns. Standard C indicates that this is unsigned. But which unsigned is this? If it’s unsigned int or unsigned long. Let’s clear this out! Consider an example:

/* type_size_t.c --  program determines type of 'size_t' */
#include <stdio.h>
int main(void)
{
    int byte_count;
 
    printf("\n*****Program shows type of size_t*****\n\n");
    printf("\"sizeof(size_t)\" returns %d bytes.\n", sizeof(size_t));
 
    if (sizeof(size_t) == sizeof(unsigned long))
        printf("\nType of \"size_t\" is \"unsigned long\".\n\n");
 
    /* Maximum value an `unsigned long int' can hold. (Minimum is 0)*/
    #  if __WORDSIZE == 64
    #      define ULONG_MAX    18446744073709551615UL
    #  else
    #      define ULONG_MAX    4294967295UL
    #  endif
 
    return 0;
}

Observe below output of program on Linux Machine:

*****Program shows type of size_t*****
 
"sizeof(size_t)" returns 8 bytes.
 
Type of "size_t" is "unsigned long".

Actually, unsigned values can never be negative! So is type ‘size_t’ values. Several, string functions, like, strlen returns value of type ‘size_t’, strn– functions, like strncpy, strncat, strncmp etc. take one of their arguments as type ‘size_t’. Also, memory functions like memcpy, memmove, memset etc. each takes its 3rd argument as type ‘size_t’. Remember that type ‘size_t’ is treated as type unsigned long on Linux. But why do we need for type ‘size_t’? We’ll see this later.

Sanfoundry Global Education & Learning Series – 1000 C Tutorials.

advertisement
advertisement
If you wish to look at all C Tutorials, go to C Tutorials.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.