-1

I can create an array of bytes like below:

test_array[3] = {0x01, 0x02, 0x03};

I want an array of bytes like above, but with random bytes. For example, I just declare that I need an array of 10 bytes. and then I get the array of size 10, but all random bytes. So that at the end, when I write:

printf("My array is: %d", test_array);

I need to see this:

{0x09, 0x15, 0xA1, 0xB2, 0xF1, 0x33, 0xBC, 0xCA, 0x1B, 0x9D};
Raza Javed
  • 65
  • 3
  • 11
  • You need to fill the array yourself with random values. 5 seconds of googling revealed e.g this: https://stackoverflow.com/questions/822323/how-to-generate-a-random-int-in-c – Jabberwocky Oct 20 '22 at 08:39
  • BTW: `printf("My array is: %d", test_array);` won't work. You cannot print an entire array, you need to do it yourself using a loop. C is not Python. I suggest you get some good beginner's C text book. – Jabberwocky Oct 20 '22 at 08:41
  • I need to fill more than 1000 bytes in my array, then filling it manually will be difficult so I was looking that maybe there exist a function so that it will be filled with random bytes. But as you mentioned it doesn't seem to be possible. Can we also fill it using loop maybe? – Raza Javed Oct 20 '22 at 09:10
  • You obviously need a loop here. This is most basic general progamming knowledge. – Jabberwocky Oct 20 '22 at 09:20

1 Answers1

0

I need to fill more than 1000 bytes in my array, then filling it manually will be difficult so I was looking that maybe there exist a function so that it will be filled with random bytes.

5 lines of code ...

unsigned char *create(void *data, const size_t size)
{
    unsigned char *ucdata = data ? data : malloc(size * sizeof(*ucdata));

    if(ucdata)
    {
        for(size_t i = 0; i < size; i++)
        {
            ucdata[i] = rand();
        }
    }
    return ucdata;
}

usage:

int main(void)
{
    unsigned char arr[5000];
    unsigned char *x;
    
    srand(time(NULL));
    create(arr, sizeof(arr));
    x = create(NULL, 150000); 

    /* ... */
    free(x);
}

So that at the end, when I write:

printf("My array is: %d", test_array);

I need to see this: {0x09, 0x15, 0xA1, 0xB2, 0xF1, 0x33, 0xBC, 0xCA, 0x1B, 0x9D};

This printf for sure will not display it. You need to iterate, but you need to do something yourself

0___________
  • 60,014
  • 4
  • 34
  • 74