Head exploding (passing array in C)
I have a C macro that that calculates the length of an array
#define length(x) (sizeof(x) / sizeof(x[0]))
In main(), I create an integer array of 10 elements. When I call that macro, I get the desired result, 10.
However, when I pass that array (created in main()) to another function, when I call the macro, I get 1. If I manually run sizeof on the passed in array, I get the size of the first element in the array. That's all well and good (and I understand why that happens), but how can I get the length of the passed in array (in C)?
Wellsie1116 posted this at 22:08 — 29th January 2009.
They have: 2 posts
Joined: Jan 2009
The problem is that sizeof is executed at compile time, not runtime. What this means is that the compiler knows the size of the array in main, because it was declared in main. But in your function, all it knows is that it has an array, but has no idea how large it is. Because it does not know how many elements are in the array, it just treats it as a pointer and returns the size of the pointer (4 in your case, and 8 in my case (64-bit os)) resulting in the wrong length of 1 (or 2 in my case).
If the size of the array will never change during runtime, why not just declare the size of the array as a preprocessor variable:
#define ARRAY_SIZE 10
then if you want to declare an array of ints:
int nums[ARRAY_SIZE];
teammatt3 posted this at 05:24 — 30th January 2009.
He has: 2,102 posts
Joined: Sep 2003
That's good to know.
This array size does change during run time. I've searched a ton of forums, and it doesn't look like it can be done. I guess I'll have to pass in the array length to every function. Not a huge deal. I just thought there would be a better way.
Wellsie1116 posted this at 15:27 — 30th January 2009.
They have: 2 posts
Joined: Jan 2009
I either just pass the length of the array along with the array or use a linked list. Both have advantages and disadvantages.
pr0gr4mm3r posted this at 19:20 — 30th January 2009.
He has: 1,502 posts
Joined: Sep 2006
Sounds like a lot of work just to get a the size of an array.
Shaggy posted this at 02:39 — 1st February 2009.
They have: 121 posts
Joined: Dec 2008
I'm no computer scientist, but I've always handled it by looking for null in the defined size of the array as the signal to stop processing. In pseudo code:
If you're filling the array sequentially
While (array element not equal null) and (in bounds of defined size of array)
do processing on element
get next element
End-While
Or not...
For all elements in the defined size of the array
if element is not null
do processing on element
end-if
End-For
Cheers,
Shaggy
Want to join the discussion? Create an account or log in if you already have one. Joining is fast, free and painless! We’ll even whisk you back here when you’ve finished.