Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate through a C array

Tags:

arrays

c

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?

like image 757
Andrew Johnson Avatar asked Oct 20 '09 23:10

Andrew Johnson


People also ask

How do you iterate through an array?

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.

How do you traverse an array while loop?

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.

How do you loop through an array without knowing the size in C?

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.

How do you iterate through an array of objects in C#?

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.


2 Answers

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.

like image 129
Variable Length Coder Avatar answered Sep 18 '22 17:09

Variable Length Coder


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.

like image 45
David Seiler Avatar answered Sep 20 '22 17:09

David Seiler