This make no sense for me:
int start_tab[2];
printf("size of an array: %d\n", sizeof(start_tab));
8
Why 8? How make it to be size of 2?
This make no sense for me:
int start_tab[2];
printf("size of an array: %d\n", sizeof(start_tab));
8
Why 8? How make it to be size of 2?
You need to divide by the size of the type like this
sizeof(start_tab) / sizeof(int)
sizeof
gives the size in bytes, since each int
is 4
bytes then two of them are obviously eight, so you can divide by the size of an int
and get the value you are looking for.
You have to do sizeof(start_tab)/sizeof(start_tab[0])
to get the number of elements in an array
Please be noted, sizeof
is an operator, not a function. sizeof
returns the size of the supplied datatype.
Why 8?
start_tab
being of type int [2]
, returns 2 * sizeof (int)
# or 8
.
How make it to be size of 2?
If you want to get the count of element in the array, simply divide the total size by the size of a single element, like
sizeof(start_tab) / sizeof(start_tab[0])
# In your platform, sizeof(int)
== 4.
Because an int is 4
bytes... so multiply by 2
makes 8
So if you want the element size divide by sizeof(int)
.
Because int
is on your platform 32 bit which is 4
bytes. You have 2
int
s multiplied with 32 bit equals 64 bit which is 8
byte. sizeof
will return the size of a datatype in bytes.
From the C Standard (6.5.3.4 The sizeof and alignof operators)
2 The sizeof operator yields the size (in bytes) of its operand, which may be an expression or the parenthesized name of a type.
Array
int start_tab[2];
occupies 2 * sizeof( int )
bytes because it has two elements and each element has type int
. So if sizeof( int )
is equal to 4
then the array occupies 8
bytes.
So you have a formula
sizeof( start_tab ) = 2 * sizeof( int )
Or in general case if an array has N elements of type T like for example
T array[N];
then
sizeof( array ) = N * sizeof( T )
Or as each element of the array has type T including the first element of the array then you can also write
sizeof( array ) = N * sizeof( array[0] )
Using this formula you can calculate N like
N = sizeof( array ) / sizeof( array[0] )
or
N = sizeof( array ) / sizeof( *array )
because *array
yields the first element of the array.