Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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_tis an unsigned type, so it cannot hold negative values - Use
%zuformat specifier for printingsize_tvalues -
SIZE_MAXrepresents the maximum value asize_tcan 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.
