0

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?

2
  • 1
    Your has_illegal_character function will only ever check the first character in the array. It also does not loop over the length of the array, but over the size of the length variable (int might be 4 bytes in your environment). Also, instead of checking the entire array every time you generate a new random value, check just that random value. Commented Oct 15, 2019 at 12:20
  • Remember to define true and false as 1 and 0, if not done yet. Commented Oct 15, 2019 at 12:37

1 Answer 1

5

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){
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I did not notice this mistake.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.