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 ?

3
  • 1
    Use printf("%zu\n" , sizeof(arr) / sizeof(arr[0]);. %d is used for int. Commented Feb 12, 2017 at 14:33
  • See the C documentation here. Commented Feb 12, 2017 at 14:35
  • using namespace std; is not valid standard C code. Commented Feb 12, 2017 at 14:56

4 Answers 4

9

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.

Sign up to request clarification or add additional context in comments.

1 Comment

And note that sizeof returns a size_t, and must be printed using the "%zu" format to avoid undefined behavior.
4

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

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

Comments

2

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.

Comments

2

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.