size_t data type in C

The size_t data type is an unsigned integral type in C that represents the size of any object in bytes. It is returned by the sizeof operator and commonly used for array indexing, loop counters, and memory size calculations. Since it represents sizes, size_t can never be negative.

Syntax

size_t variable_name;
const size_t variable_name = value;

Where variable_name is the name of the variable of type size_t.

Example: Basic Usage of size_t

Here's an example demonstrating size_t for array operations and size calculations −

#include <stdio.h>
#include <stddef.h>
#include <stdint.h>

int main(void) {
    const size_t x = 150;
    int a[x];
    
    // Using size_t for loop counter
    for (size_t i = 0; i < x; ++i) {
        a[i] = i;
    }
    
    printf("SIZE_MAX = %zu<br>", SIZE_MAX);
    size_t size = sizeof(a);
    printf("Array size = %zu bytes<br>", size);
    printf("Number of elements = %zu<br>", size / sizeof(int));
    
    return 0;
}
SIZE_MAX = 18446744073709551615
Array size = 600 bytes
Number of elements = 150

Example: size_t with String Functions

Many standard C functions like strlen() return size_t

#include <stdio.h>
#include <string.h>

int main(void) {
    char str[] = "TutorialsPoint";
    size_t length = strlen(str);
    
    printf("String: %s<br>", str);
    printf("Length: %zu characters<br>", length);
    printf("Memory used: %zu bytes<br>", sizeof(str));
    
    return 0;
}
String: TutorialsPoint
Length: 14 characters
Memory used: 15 bytes

Key Points

  • size_t is an unsigned type, so it cannot hold negative values
  • Use %zu format specifier for printing size_t values
  • SIZE_MAX represents the maximum value a size_t can hold
  • It's the recommended type for array indices and loop counters dealing with sizes

Conclusion

The size_t data type is essential for safe memory and array operations in C. It ensures portability across different systems and prevents negative indexing errors, making it the preferred choice for size-related operations.

Updated on: 2026-03-15T09:55:04+05:30

9K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements