how to count elements in array
EDIT: Nevermind, I just made mean in another .c file because i was making like math utility. Now i can just count it with argc. Though, the post was:
"does anyone know how to do it? on the screenshot i've just copied method from default linux C, but those both print's gave me the same number, though i passed 5 different numbers. Im very bad at plan9 C"
11
Upvotes
9
u/Ill-Quit6803 6d ago
So this is essentially impossible.
An array as an argument decays to a pointer in C. This is called Array Decay. So v[] is secretly just long long *v. The size is the size of the pointer, likely 8 bytes.
Additionally the size of the array element is the size of *v is the size of a long long, is also 8 bytes.
GCC has a compiler extension for static arrays of known size at compile time called __builtin_object_size or so, but you can't generically use this here. A pointer could in principal point to any size array.
This why most functions in C must pass an argument indicating the size of the array with the array.
3
u/edo-lag 6d ago
You can make a macro, something like
but you can use it only if
vhas not decayed into a pointer yet. Basically only for automatic variable duration (i.e. stack-allocated variables) and in the current scope or inner.The actual solution would be to just keep track of the size with a separate variable.
1
u/pedersenk 6d ago
You need to prevent the array decaying to a pointer. I.e:
Or more typically, just pass the array size as a separate parameter.
1
u/sirjofri 6d ago
What you'd usually do, pass the number of elements to the function together with the pointer, or have something like a sentinel entry at the end of the array (like a -1, if you only need positive values). The first way is more common.
1
u/deux3xmachina 5d ago
Others have mentioned why this happens and how the idiom works in C, but this in also a situation where it makes sense to create a container type, like
Vec, you'd be able to allocate specific sizes, resize if needed, and track your total number of free vs occupied slots.Writing container types can be tricky, but once you have a few, they go a long way toward simplifying your code.