Pritpal
Pritpal

Reputation: 591

Behaviour of Sizeof in C

I have learnt that when we pass the array name to sizeof, the name of the array does not decay to the pointer to base address. The code below verifies this fact by giving answer 10.

#include <stdio.h> 

int main(){  
    int arr[10];  
    printf("Size of array is %d" , sizeof(arr)/sizeof(int));  
    return 0;  
}

However when I run the code below, the answer comes 1. Irrespective of whether a dimension is written in prototype or not , the answer is 1. Why is it so ?

#include <stdio.h>

void dimension(int arr[]){  
    printf("Sizof array is %d" , sizeof(arr)/sizeof(int));  
}


int main(){  
    int arr[10];  
    dimension(arr);  
    return 0;  
}  

Upvotes: 6

Views: 855

Answers (7)

Mehmet Fatih Tabak
Mehmet Fatih Tabak

Reputation: 11

Because you're passing an unknown size array.

Upvotes: 0

Sebastian Mach
Sebastian Mach

Reputation: 39089

In

void dimension(int arr[]){  
    printf("Sizof array is %d" , sizeof(arr)/sizeof(int));  
}

arr[] decays to a pointer, therefore you have the equivalent of

printf("Sizof array is %d" , sizeof(int*)/sizeof(int));

and because on your platform, sizeof(int*) == sizeof(int), you receive 1 as the result.

Note however, that for variable length arrays, sizeof becomes a runtime operation:

int main () {
    int i = ...;
    int x[i];
    printf("number of elements: %d", sizeof (x) / size(*x));
}

Upvotes: 2

MByD
MByD

Reputation: 137322

When array is passed to a function, it is passed as a pointer, not an array, so the sizeof(arr) will return sizeof(int *)

Upvotes: 3

unkulunkulu
unkulunkulu

Reputation: 11912

This signature

void dimension(int arr[])

is absolutely equivalent to

void dimension(int *arr)

See also Question 6.4

Upvotes: 6

Rudy Velthuis
Rudy Velthuis

Reputation: 28806

Arrays as function arguments do decay to pointer, though. Since this happens before sizeof() is called, you can't prevent it.

Just think about it: how can sizeof() know the size of an array if any size array can be passed and no extra info is available? You get sizeof(pointer), and that seems to be the same size as an int, in your setup.

Upvotes: 1

littleadv
littleadv

Reputation: 20272

Because you pass an array of unknown size which is equivalent to a pointer in this context. sizeof is calculated at compile time, not runtime.

Upvotes: 5

DhruvPathak
DhruvPathak

Reputation: 43235

because arr is a pointer, which is an integer .

Upvotes: 0

Related Questions