Behaviour of Sizeof in C

本小妞迷上赌 提交于 2019-11-28 00:13:42

This signature

void dimension(int arr[])

is absolutely equivalent to

void dimension(int *arr)

See also Question 6.4

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.

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

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));
}

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.

because arr is a pointer, which is an integer .

It returns the size of the pointer, which is integer.

Because you're passing an unknown size array.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!