size_t là kiểu số nguyên không dấu (unsigned integer type) dùng biểu diễn kích thước đối tượng tính bằng byte. Trả về bởi toán tử sizeof. Dùng cho array indexing, loop counter, memory size. Không bao giờ âm.
Cú pháp
size_t var_name;
Định nghĩa trong <stddef.h>, <stdio.h>, <stdlib.h>, <string.h>...
Ví dụ
#include <stdio.h>
#include <stddef.h>
#include <stdint.h>
int main() {
const size_t x = 150;
int arr[x]; // VLA (C99)
for (size_t i = 0; i < x; ++i)
arr[i] = i;
printf("SIZE_MAX = %zu\n", SIZE_MAX);
size_t sz = sizeof(arr);
printf("Kich thuoc mang: %zu bytes\n", sz);
return 0;
}
Kết quả (64-bit)
SIZE_MAX = 18446744073709551615
Kich thuoc mang: 600
Giải thích: size_t x = 150 dùng làm kích thước VLA. Duyệt mảng bằng size_t i (khớp kiểu). SIZE_MAX là max giá trị của size_t (2^64-1 trên 64-bit). sizeof(arr) = 150 * 4 = 600 bytes.
Đặc điểm quan trọng
- Kích thước phụ thuộc platform: 32-bit -> 4 bytes, 64-bit -> 8 bytes.
- Format specifier:
%zu(C99),%lu/%llu(cũ). - Tránh so sánh
size_tvớiintâm (implicit conversion -> số lớn dương). - Hàm thư viện trả về
size_t:strlen,strcspn,sizeof,offsetof...