Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fill a string with random (hex) characters?

Tags:

c

linux

I have a string (unsigned char) and i want to fill it with only hex characters.

my code is

unsigned char str[STR_LEN] = {0};
for(i = 0;i<STR_LEN;i++) {
    sprintf(str[i],"%x",rand()%16);
}

Of course, when running this I get segfaulted

like image 653
fazineroso Avatar asked Aug 24 '12 13:08

fazineroso


1 Answers

  1. string is an array of char-s not unsigned char-s
  2. you are using str[i] (which is of type unsigned char) as a 1st argument to sprintf, but it requires type char * (pointer).

This should be a little better:

char str[STR_LEN + 1];
for(i = 0; i < STR_LEN; i++) {
    sprintf(str + i, "%x", rand() % 16);
}
like image 78
Jan Spurny Avatar answered Sep 18 '22 08:09

Jan Spurny