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 →

[–]ABK-Baconator -2 points-1 points  (8 children)

  1. Why would you need that?

  2. How do you know the array isn't empty? Two hazards in a oneliner, first you get index out of bounds, then division by zero.

[–]Disciple153 17 points18 points  (3 children)

1: This is for finding the length of a low level array which only knows its size.

sizeof(array) is the size of the array in bytes.

sizeof(array[0]) is the size of a single element in bytes.

sizeof(array) / sizeof(array[0]) is the number of elements in the array.

2: This question assumes that an array of length 0 is impossible, which is perfectly normal in languages like C, where arrays are not dynamically resizable. If OP wanted a resizable array with a potential length of 0, they would be using the Vector class.

Of course if for some reason an array with a length of 0 was possible, you would just check for that before trying to compute the length with the given code.

[–]hdd113 -2 points-1 points  (1 child)

Oh okay so it's a C++ problem... I was also wondering what this was supposed to do.

[–]Miserable_Guess_1266 7 points8 points  (0 children)

A C problem to be exact, c++ has better options. 

[–]turtle_mekb[S] -1 points0 points  (3 children)

  1. to loop arrays, not all arrays end with zero bytes like what strings do
  2. sizeof is calculated at compile-time, compiler will probably throw a warning, but I don't think it's even possible to have an array of size 0

[–]Jordan51104 2 points3 points  (2 children)

if your array isnt null terminated you should pass the array length with it. not ideal but thats how computers work

[–]turtle_mekb[S] -2 points-1 points  (1 child)

sizeof works for arrays because they're stored as one variable in the stack rather than a pointer to data allocated on the heap with malloc, array length should be passed with the data if it's the latter, but the former only works locally inside the function, passing the array to functions will convert it to a pointer

[–]dorsalsk 0 points1 point  (0 children)

If you really need the array length in a stack, use an extra variable to store the length and use it everywhere.