-4

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?

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
krzyhub
  • 6,285
  • 11
  • 42
  • 68
  • sorry, I used to programming in higher languages and this seems to be obvious, but now I am too mad for just reading. – krzyhub Apr 07 '15 at 20:14
  • possible duplicate of [Operator sizeof() in C](http://stackoverflow.com/questions/3334233/operator-sizeof-in-c) – Fiddling Bits Apr 07 '15 at 20:22

6 Answers6

3

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.

Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
3

You have to do sizeof(start_tab)/sizeof(start_tab[0]) to get the number of elements in an array

Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
Mateo Hrastnik
  • 533
  • 1
  • 7
  • 20
3

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.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
2

Because an int is 4 bytes... so multiply by 2 makes 8 So if you want the element size divide by sizeof(int).

Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
rfkortekaas
  • 6,049
  • 2
  • 27
  • 34
2

Because int is on your platform 32 bit which is 4 bytes. You have 2 ints multiplied with 32 bit equals 64 bit which is 8 byte. sizeof will return the size of a datatype in bytes.

Fiddling Bits
  • 8,712
  • 3
  • 28
  • 46
TobiSH
  • 2,833
  • 3
  • 23
  • 33
2

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.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335