top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

What should be sizeof(array) in C

0 votes
472 views

My array has five elements i.e. integers and when I print sizeof(arr); it gives me 20. I am expecting it to be 5 can someone clarify why it is 20.

posted Jul 4, 2014 by anonymous

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

2 Answers

+2 votes
 
Best answer

The size of an integer is 4 bytes. So int array[5] means an array of 5 integers of 4 bytes each.
So sizeof(array) = 4 x 5 = 20 bytes.

Similarly the size of a character is 1 byte. And char array[5] means an array of 5 characters of 1 byte each.
So sizeof(array) = 1 x 5 = 5 bytes.

Hope this helps.

answer Jul 4, 2014 by Ankush Surelia
0 votes

It should give you 20 as sizeof will return the length of the array * size of one element in memory which is 5 * 4 in your case.

answer Jul 4, 2014 by Tapesh Kulkarni
Similar Questions
+1 vote

A lot of programs contain a definition like the following one:

#define ARRAY_SIZE(a) (sizeof(a) / sizeof(*a))

If this is applied to a pointer instead of an array, this still compiles and the result is wrong.

I wonder if there is a kludge we can apply to make this fail to compile. Warning about the sizeof(a) / sizeof(*a) construct when a is not of array type might make sense as well.

+2 votes
#include <stdio.h>

int main(void)
{
  int a=17;
  scanf("%d",&a);

  int arr[a];

  printf("%lu",sizeof(arr));
}

Memory for array "arr" should be allocated at compile time but in this case it takes the value of "a" from the user(run-time) and allocates the same size for the array.

...