I have an array of structs that I created somewhere in my program.
Later, I want to iterate through that, but I don't have the size of the array.
How can I iterate through the elements? Or do I need to store the size somewhere?
Iterating over an array You can iterate over an array using for loop or forEach loop. Using the for loop − Instead on printing element by element, you can iterate the index using for loop starting from 0 to length of the array (ArrayName. length) and access elements at each index.
Using while to iterate over an arrayFirst we define an array and find out its length, len , using the length property of arrays. Then we define an index variable to iterate over the array . The while loop, from lines 6 to 9, is run till index becomes equal to len indicating that the entire array is traversed.
You cannot iterate over an array in c without knowking the number of elements. Please note that sizeof(array) / sizeof(array[0]) won't work on a pointer, i.e it will not give the number of elements in the array.
In c#, the Foreach loop is useful to loop through each item in an array or collection object to execute the block of statements repeatedly. Generally, in c# Foreach loop will work with the collection objects such as an array, list, etc., to execute the block of statements for each element in the array or collection.
If the size of the array is known at compile time, you can use the structure size to determine the number of elements.
struct foo fooarr[10]; for(i = 0; i < sizeof(fooarr) / sizeof(struct foo); i++) { do_something(fooarr[i].data); }
If it is not known at compile time, you will need to store a size somewhere or create a special terminator value at the end of the array.
You can store the size somewhere, or you can have a struct with a special value set that you use as a sentinel, the same way that \0
indicates the end of a string.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With