1

Suppose I have an array, defined as

int arr[10]; 

I want to progressively fill this array (assuming to not run out of the memory allocated for the array), according to a loop of the form

for(int i = 0; i < some_number; i++) if(some_condition) add_element_to_arr 

What is the best way to do this? Two methods I can think of are 1) using an auxiliary variable to remember the number of stored values, or 2) using a pointer to do the same thing.

What is the preferred/standard/conventional way to do this?

Also, having to do this kind of operations for multiple arrays, to remember how many values have been added to each array one has to use an auxiliary variable for each array. What is the preferred way to deal with this?

2 Answers 2

5

You could use a pos variable like this:

for(int i = 0, pos = 0; i < some_number && pos < 10; i++) if(some_condition) arr[pos++] = i; 

No need to use a pointer in this case.

Update:

With multiple arrays (different sizes), you could create a struct with a pointer to the array and a current position, this way both values always stay together:

struct arr_data { int *arr; int current_pos; } 

And add a size too maybe:

struct arr_data { int *arr; int size; // or unsigned int or size_t int current_pos; // or unsigned int or size_t } 

You could then create an array of those structs, depending on the implementation.

Sign up to request clarification or add additional context in comments.

5 Comments

because otherwise you could have "holes" in your array. i.e. your array could look like [1,5,null,null,null,5,6....]
@rbp - Because an element isn't always added in each iteration.
is there a specific reason to prefer this way over using a pointer, also taking into account scenarios with larger arrays? Also, if you have to do this kind of operation for lots of arrays, you have to mantain a pos variable for each one. Is there some standard way to deal with this?
@glS - I think it's cleaner and less error prone (and the size of the array doesn't matter). With multiple arrays, you could create a struct with a pointer to the array and a current position, that way both values stay together.
@Danny_ds thanks. I also appreciate the simple struct example
1

if you want to make this some standard in your program, you could use something like:

struct progressiveArr{ int elements[10]; int size; } and then: for(int i = 0; i < some_number i++) if(some_condition) { arr.elements[arr.size++]=i; } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.