Array size

Posted By: Fenriswolf

Array size - 12/03/07 19:59

Hello,

how can I get the size of an array?

I have tried the following:

var my_array[7];
...
size = sizeof(my_array) / sizeof(my_array[0]);

However, sizeof(my_array[0]) leads to an engine crash.

Thanks
Posted By: Joozey

Re: Array size - 12/04/07 08:43

What do you mean with size, amount of indexes? Then what are you trying to achieve with sizeof(my_array[0])?

Furthermore, this is what the manual says about sizeof():
Quote:


The sizeof() function returns the size of a variable or a struct in bytes. This can be used to initialize structs through the zero macro that is defined in include\acknex.h





If you want to have the amount of indexes an array contains, you have to make your own function because as far as I'm aware, lite-c does not have such a function yet.

Not tested code which is inevitebly wrong, but it's about the concept:
Code:

int getArrayLength(var array) {
int n = 0;
while (array[n]){n++}
return n;
}


Posted By: Fenriswolf

Re: Array size - 12/04/07 09:52

Hi,

Quote:

What do you mean with size, amount of indexes?



Yes, I've meant the number of elements.

Quote:

Then what are you trying to achieve with sizeof(my_array[0])?



I wanted to calculate the size of a single array element in bytes.
Dividing the array size in bytes by the element size in bytes should result the array's length in elements, if I'm not mistaken.
If arrays are handled as pointers this would not work, though.


Your code works fine, thank you!
However, the last element of the array has to be NULL; otherwise a wrong value is returned:

var my_array[3] = { 1, 2 } // works
var my_array[3] = { 1, 2, 3 } // does not work
Posted By: Joozey

Re: Array size - 12/04/07 17:47

Quote:


Dividing the array size in bytes by the element size in bytes should result the array's length in elements, if I'm not mistaken.





Good point, hadn't thought of that idea. But I think arrays are indeed handled as pointers. I don't see a good solution for this at the moment, you'll just have to add NULL in every array I guess, or somehow store the index of each array at game start.
Posted By: Futurulus

Re: Array size - 12/04/07 18:06

Quote:

I think arrays are indeed handled as pointers.



Yeah -- I don't know about in Lite-C in this case, but in a conforming C compiler
Code:
sizeof(MyArray) / sizeof(MyArray[0])

would probably return 1 on a 32-bit system, because sizeof(a pointer) = 4 and sizeof(a var) = 4.
Posted By: Fenriswolf

Re: Array size - 12/05/07 08:08

Thank you both for your help!
Probably I will either use the getArrayLength function or pass the array length as a parameter.
These are the best solutions I can think of at the moment.
© 2024 lite-C Forums