top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Sizeof is resulting different output for the different function for an array?

+2 votes
162 views

See the following program, sizeof is resulting different output for the different function. Can someone explain this/

#include<stdio.h>

void main()
{
    int arr[]={1,2,3,4,5};
    printf("length: %d\n",sizeof(arr));
    printf("length: %d\n",sizeof(arr)/sizeof(int));
    show(arr);
}

void show(int ar[])
{
   printf("length: %d\n", sizeof(ar));
   printf("length: %d\n", sizeof(ar)/sizeof(int));
}

Output

length: 20
length: 5
length: 4
length: 1
posted May 7, 2015 by anonymous

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

1 Answer

+2 votes
 
Best answer

Here size of an integer variable is 4 . In main function, arr is declared as an array and sizeof returns size of an array. Size of an array is equal to (# of element * size of one element). That's why first statement is returning length = 20.

When an array is passed to a function, it is received as an pointer and pointer size is 4 bytes. That's is the reason length = 4 in show function.

answer May 8, 2015 by Harshita
Similar Questions
0 votes

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.

0 votes

Used the sizeof of function, which gives 1; why?
I want to know the size of the entire function. How to achive it?

#include <stdio.h>
void (*p)(int); 
void test_func(int data)
{
  printf("%d\n",data);
}

main(void)
{
    p = test_func;
    (*p)(4);
    printf("%d",sizeof(test_func));
}
...