2

I have initialized an array of size 10 but on printing the sizof array shows 40 . The code is as follows ,

#include <iostream>

using namespace std;

int main() {
    int  arr[10] =  {2,4,5,6,7,8,9,6,90};

        printf("%d \n" , sizeof(arr));

}

Output :

/Users/venkat/Library/Caches/CLion2016.1/cmake/generated/InsertionSort-e101b03d/e101b03d/Debug/InsertionSort
40 

Process finished with exit code 0

What does C prints 40 here ?

athavan kanapuli
  • 462
  • 1
  • 6
  • 19

4 Answers4

8

sizeofreturns the size of the array in memory, not the length of the array. Then since sizeof(int) is 4 bytes and your array has 10 int values, its size is 40.

Lopan
  • 483
  • 1
  • 7
  • 20
  • And note that sizeof returns a size_t, and must be printed using the "%zu" format to avoid undefined behavior. – Jens Feb 12 '17 at 14:35
2

Your array contain 10 ints. 10 * sizeof(int)

int here is 32 bits = 4 bytes. 4*10 = 40. Simple math

Tony Tannous
  • 14,154
  • 10
  • 50
  • 86
1

Because sizeof is a built in operator that works on the type of the expression. For arrays (and not pointers) it will print sizeof(array_element_type) * array_length.

On your system, it must be that sizeof(int) is 4.

And once you get excited over learning that

sizeof(array)/sizeof(array[0]) == array_length

bear in mind that once you pass the array into a function, it will decay to a pointer and that will no longer hold.

StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458
1

You need to divide sizeof (arr) by the size of one element: sizeof (arr)/ sizeof (arr[0])

This because sizeof(arr) shows the number of bytes the argument is made of, i.e. sizeof(int) * array dimention

Baffo rasta
  • 320
  • 1
  • 4
  • 17