size_t in C
This tutorial will discuss using the size_t
command to define an unsigned data type variable in C.
the size_t
in C
The size_t
command defines an unsigned data type variable in C. An unsigned data type cannot be negative, so the size_t
command is a data type like int
and is used in the case of positive integer values.
For example, if we want to count something or find the length of an array, we can use the size_t
command to define a variable that will hold a positive value because the counting and the length of an array start from 0, and it cannot be negative.
The sizeof()
function returns the size of a number in bytes, and we can use the size_t
command to store the value returned by the sizeof()
function.
The size_t
data type uses at least 16-bit memory to store a value.
The return type of many function like strcspn()
and strlen()
function is of data type size_t
. To use the size_t
data type, we must include the stddef.h
and stdint.h
header files because the size_t
data type is dependent on these two header files.
For example, let’s define an array and find its size using the sizeof()
function and store it in a variable of size_t
data type. See the code below.
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
int main(void) {
const size_t len = 100;
int My_array[len];
for (size_t i = 0; i < len; ++i) My_array[i] = i;
size_t size = sizeof(My_array);
printf("size of array = %lu\n", size);
}
Output:
size of array = 400
In the above code, the len
variable is used to store the length of the array, and we used a for
loop to fill the array My_array
. We used the printf()
function to print the size of the given array.
We used %lu
string inside the printf()
function because the output of the sizeof()
function is a long unsigned integer of type size_t
.
We used the \n
string inside the printf()
function to add a new line after the value of the size
variable is printed, or the cursor will move to the new line.
We can use the size_t
data type to store the size of an object, and if we want to store some other value that can also be negative, we should use another data type like int
.
If we want to find the difference between two size_t
data type values, we cannot find the exact result in some cases; if the first value is less than the second value, the result should be negative, but the result will be positive in this case because the difference is calculated between two unsigned values.
In this case, we have to use another data type like int
or float
. If the size_t
data type implementation is 64-bit, it will be 64-bit wide; if the implementation is 32-bit, it will be 32-bit wide, and so on.