pietjanssen
pietjanssen

Reputation: 31

How do I loop over an array in a function in C?

I want to generate a 16 byte long unsigned char array and fill it with random chars except some.

I am a noob in C still, and I still don't understand when to use pointers and such to correctly use arrays yet.

What I have right now:

bool has_illegal_character(uint8_t * arr, int length){
    for(int i=0; i<sizeof(length); i++){
        if (*arr == 0x01) return true;
        else if (*arr == 0x04) return true;
        else if (*arr == 0x05) return true;
        else if (*arr == 0x15) return true;
        else if (*arr == 0x00) return true;
    }
    return false;
}

uint8_t arr[16] = {0};
while(has_illegal_character(arr, sizeof(arr))){
   for(int i = 0; i < sizeof(arr; i++)
   {
        arr[i] = rand() % 255;
   }
}

This does not work.

What is the correct way to create an array filled with random characters except 0x01, 0x04, 0x05 and 0x15, ideally by using a function in C?

Upvotes: 0

Views: 70

Answers (1)

unwind
unwind

Reputation: 399753

This:

for(int i=0; i<sizeof(length); i++){
                 ^
                 |
                wut

Is not correct, you're not interested in looping over the bytes of length itself. It should just be:

for(int i = 0; i < length; ++i){

Upvotes: 5

Related Questions