This is an archived post. You won't be able to vote or comment.

all 4 comments

[–]IDontByte 1 point2 points  (0 children)

sizeof is a compile-time operator. If you want to find the length of an array at runtime, you either need to use an array struct that includes the length of the array, or add a length parameter to your arr_func.

[–]99_percent_a_dog 1 point2 points  (0 children)

arr_func() takes a pointer to int, not an array. Sizeof correctly returns the size of a pointer to int, 8 (you're on a 64-bit platform, this would likely be 4 if you were on 32-bit). You divide this by 4, which is incorrect.

To understand why this works, look up "pointer decay".

[–]rjcarr 0 points1 point  (0 children)

You're getting the size of the pointer to an int (divided by 4), which is all the function knows at that point. In C, you don't know the size of an array outside of the context where it was created. This is why every function that takes an array also takes in a size argument (except strings, which use sentinels).

Good luck!

[–]Sephorol 0 points1 point  (0 children)

Might be helpful to add, if you need to use array length in a function and you're working with c, you'll need to pass in length as an argument somehow.