Array counting in C
Hi, another pointless exercise (because we should have always counted the size of the array), but...
Here's a little demo: Code:
#include <stdio.h> cheers! |
My guess: in the function definition, 'a' is a pointer hence has the length of a pointer. Think it always returns 1.
|
Function alen()'s parameter is not actually an array; it's a pointer. This is not a bug; it's a feature. An array does not have stored, at runtime, its size or number of elements, so there's no way (as your code is written) for the function to know the size of the array.
To be consistent, C uses a pointer even if the size of the array would be known at compile time. This program, for example, outputs "4" as its result, which is the size of a pointer on my machine. Code:
#include <stdio.h> |
So if I pass a pointer (to an array) how can I tell when it's 'NULL' if I iterate through it?
Code:
while(*a++ != NULL) |
Hi,
Quote:
|
Even if I pre-init it, then assign it to point to the start of the array, that would overwrite out the previous state.
How do you tell when the array has finished...? |
Quote:
|
So, there's many ways of doing it, but no way of doing it without any pre-arrangement?
No way of checking for a valid pointer? A [-1] goes backwards and the pointers can always increment, so can't check there either. Got to be in the know it seems. Not very dynamic, even though we should always know the size of things, or have a prearranged EOF/NULL/id, etc... Cheers anyway... |
Quote:
Quote:
Because there are always tradeoffs ... always advantages and disadvantages ... ... and *you* should be able to choose the method that works *best* for your particular application. Suppose, for example, the language had a length byte before the start of the array. Voila - you always know your array size. But you could only hold up to 255 elements (8 bits). OK - suppose the language stored the length in an integer. Now your array could hold up to 4 billion elements ... but you'd be "wasting" a lot of extra space. And what if you needed a "stretchy" array, that could grow or shrink? The list goes on and on - I hope you get the idea. IMHO .. PSM |
Yeah...
I'm just investigating the 'limits' of c, especially when it comes to arrays and pointers. Even though at some point I will always 'know' the length of something, I just like the ability to find something out... or even prove it... y'know |
Quote:
|
All times are GMT -5. The time now is 01:41 AM. |