Tomáš Šíma
Tomáš Šíma

Reputation: 864

Cycle through certain range in array in C

I have this code

int x = 0
int MAX = 21;
int MIN = 18;
char *arr[40];
do{
  char* current = cycle(x,arr)
  x++;
}while(x<10000000)

My cycle() currently cycles through entire array

unsigned char *cycle(int counter, unsigned char *packets[40]){
int tmp = counter % 40;
return packets[tmp];
 }

But I want it to cycle in array just in [MIN,MAX] range. So the return values in while loop are: arr[18], arr[19], arr[20], arr[21], arr[18], arr[19]...

Any idea how to implement this? I don't want solutions using global variable.

Thanks for help!

Upvotes: 0

Views: 265

Answers (2)

Adeel Ahmed
Adeel Ahmed

Reputation: 1601

unsigned char *cycle(int counter,int min, int max, unsigned char *packets[40]){
    int tmp = (counter % (max - min + 1)) + min;
    return packets[tmp];
}

Upvotes: 0

Kos
Kos

Reputation: 72241

Try something like this:

sometype cycle_range(int counter, sometype array[], unsigned min, unsigned max) {

    sometype* first = array+min;
    unsigned length = max-min+1;

    return first[counter % length];
}

This works just like your solution, but it starts min elements further in array and loops over max-min+1 elements instead of 40.

(sometype is unsigned char* in your case, but you can substitute another type here if you want)

Upvotes: 2

Related Questions