My code returns non ASCII characters and I am not sure why.
Wrong scale used to generate lower case letters.
(122 * drand48()) + 97
converted to an integer type can readily make 122 different values. [97...218]. This is outside the ASCII range of [0...127]
.
How do I set a random number of random lowercase character ...
drand48()
provides a random value [0...1.0). Scale by 26 and truncate to get 26 different indexes.
int index = (int) (drand48()*26); // 0...25
Pedantic code would be concerned about the few random values that may round the product to 26.0
if (index >= 26) index = 26 - 1;
int az = index + 'a';
// or look up in a table if non-ASCII encoding might be used
// 12345678901234567890123456
int az = "abcdefghijklmnopqrstuvwxyz"[index];
Selecting a random length would use the same thing, but with NUMLTRS
instead of 26.
int length = (int) (drand48()*NUMLTRS);
if (index >= NUMLTRS) index = NUMLTRS -1;
... to a Struct member using memset in C
It is unclear if dns_name[]
should be all the same, or generally different letters.
struct Record foo;
if (all_same) [
memset(foo.dns_name, az, length);
} else {
for (int i = 0; i < length; i++) {
int index = (int) (drand48()*26); // 0...25
if (index >= 26) index = 26 -1;
int az = index + 'a';
foo.dns_name[i] = az; // Does not make sense to use memset() here
}
}
Lastly, if dns_name[]
is meant to be a string for ease of later use, declare with a +1 size
dns_name[NUMLTRS + 1];
// above code
foo.dns_name[NUMLTRS] = '\0'; // append null character
printf("dna_name <%s>\n", foo.dns_name);