glS
glS

Reputation: 1299

What is the best way to progressively fill an array in C?

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?

Upvotes: 1

Views: 498

Answers (2)

Danny_ds
Danny_ds

Reputation: 11406

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.

Upvotes: 5

Or Yaniv
Or Yaniv

Reputation: 571

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;   
}

Upvotes: 1

Related Questions