The C sizeof operator accepts exactly one argument and returns its size, measured in bytes. The result from the operator is of type size_t, which is defined in the header <stddef.h>.
Advertise on this site. I promise you will like the rates :)
sizeof is an unary operator, meaning that it accepts exactly one argument (operand). Depending on the operand, you will or you won’t need to use parenthesis around it:
You can use it to get the size of any type:
..or get the size of an expression:
Do not use the C sizeof operator with:
Here you can check the size of any type.
sizeof(char); //This will always return 1:
You can test and print the size of the different data types like this:
Note for the last example: We will not get the number of elements in the array, nor the size of the int type. What we will get is the actual amount of memory, needed to store the array. It is equal to the number of elements multiplied by the size of the array type. On my computer this is 15 * 4 = 60 Bytes.
In C, the standard way to get the number of elements in an array is like this:
int elementsCount = sizeof arrayName / sizeof arrayName;
In other words, we divide the size of the array by the size of one element. Logically, the result is the number of elements in that array.
Note: this will not work in a function that received the array as a parameter. That’s because the actual parameter is a pointer to the array and not the array itself. This is the reason why in C you should always pass the size of the array as a complementary argument to the array.