Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does #define ArrayLength(x) (sizeof(x)/sizeof(*(x))) mean?

Tags:

arrays

c

pointers

What does this line exactly mean?

It is clear what define is, but I don't understand why is passing the pointer of x at the denominator:

#define ArrayLength(x) (sizeof(x)/sizeof(*(x)))

thanks

like image 211
aneuryzm Avatar asked Jan 18 '23 19:01

aneuryzm


1 Answers

The denominator

sizeof(*(x))

is the length of the first element in the array in bytes. The variable x is of an array type, and it decays to a pointer, pointing to the start of the array. The asterisk (*) is the dereference operator, so *(x) means "the data pointed to by x".

The numerator

sizeof(x)

applies the sizeof operator to an array type. This gives the length of the entire array in bytes.

The macro could also be written as

#define ArrayLength(x) (sizeof(x)/sizeof(x[0]))

which is perhaps easier to read.

like image 196
makes Avatar answered Jan 29 '23 03:01

makes