Why the pointer hack for finding the size of an array in C giving different value when used in a called function [duplicate]

  • A+

This question already has an answer here:

This is the code below to illustrate the issue:

#include <stdio.h>  void func(int arr[]);  int main() {     int arr[10];     int n = *(&arr + 1) - arr;     printf("%d/n", n);     func(arr);     return 0; }  void func(int arr[]) {     int n = *(&arr + 1) - arr;     printf("%d/n", n); } 

Output of the above code is:

10 268435906 


Despite the syntax used for its definition void func(int arr[]), function func receives a pointer to the first element of the array. The definition is clearer as void func(int *arr).

The expression *(&arr+1)-arr evaluates to the number of elements of an array at compile time only if arr is defined as an array. If arr is a pointer, it dereferences memory after the pointer and subtracts the pointer value, which is meaningless and in most circumstances has undefined behavior.

A more common (and more readable) expression to get the number of element of an array is

n = sizeof(arr) / sizeof(*arr); 

If arr is an array, dividing its size in bytes by the size of an element in bytes produces the number of elements. The expression is evaluated at compile time, no runtime overhead. If arr is a pointer, dividing its size by the size of the type it points to is defined, but useless, just like your expression.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: