Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

issue with length macro [closed]

Tags:

c

macros

I have a simple macro:

#define LENGTH(arr) (sizeof(arr)/sizeof(arr[0]))

and for whatever reason, it seems to work fine when setting something like:

int length = LENGTH(arr)

but not to compare with in a loop

while(i < LENGTH(arr))
like image 444
Brian Maher Avatar asked Dec 30 '25 01:12

Brian Maher


2 Answers

For the same arr, the macro will either work or it won't.

The likely problem is that the arr in the loop is a pointer rather than an array. The macro does not work with pointers, it only works with arrays.

like image 184
NPE Avatar answered Jan 01 '26 13:01

NPE


Remember that arrays decays to pointer when passed around. So if you pass an array to a function, it's not longer an array but a pointer inside the function. A pointer which have only have information about the type, but not the size of the array.

like image 45
Some programmer dude Avatar answered Jan 01 '26 15:01

Some programmer dude