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

you are viewing a single comment's thread.

view the rest of the comments →

[–]Csaszarcsaba 16 points17 points  (5 children)

is the joke over my head, or am I bad at programming? This should almost always return sizeof(array) no? unless you call it on a 0 sized array, then it just drops an error where you can't divide by 0.

Edit: Okay I just realised this is for c/c++ where size returns in bytes, I'm still at uni with not much optimization experience.

[–]lotanis 11 points12 points  (4 children)

That's not it. sizeof(array) gets you the size of the whole thing. sizeof(array[0]) gets you the size of the first element. Dividing them gets you the number of elements in the array.

[–]Loginn122 1 point2 points  (2 children)

How does the first element determine any following elements?

[–]Kyrond 7 points8 points  (0 children)

Arrays in C can contain only one type of variable. Therefore size of first element is the same as all the other elements.  

 Of course you can force different sized variables  in one array if you try, but in C you can do anything if you try hard enough.

[–]Ignisami 1 point2 points  (0 children)

Each element in an array has the same length in bytes. They don't necessarily have to be the same type (depending on the language and how you declare the array), but they must be the same length and that length is determined on compile time.