简体   繁体   English

如何在C中使用memset为Struct成员设置随机数的随机小写字符

[英]How do I set a random number of random lowercase characters to a Struct member using memset in C

I am forced to use memset and drand48() to set a random number (2 - 7) of random characters that are lower case letters ('a' to 'z'). 我被迫使用memset和drand48()设置随机数(2-7个),这些随机数是小写字母(“ a”至“ z”)。 My code returns non ASCII characters and I am not sure why. 我的代码返回非ASCII字符,我不确定为什么。

struct Record {
    int seqnum;
    float threat;
    unsigned int addrs[2];
    unsigned short int ports[2];
    char dns_name[NUMLTRS];
};

My code is in a for loop: 我的代码在for循环中:

memset(rec_ptr[i].dns_name, (char)((122 * drand48()) + 97), 
((sizeof(char) * 7) * drand48()) + (sizeof(char) * 2));

My code returns non ASCII characters and I am not sure why. 我的代码返回非ASCII字符,我不确定为什么。

Wrong scale used to generate lower case letters. 用于生成小写字母的比例错误。

(122 * drand48()) + 97 converted to an integer type can readily make 122 different values. (122 * drand48()) + 97转换为整数类型可以很容易地使122个不同的值。 [97...218]. [97 ... 218]。 This is outside the ASCII range of [0...127] . 这超出[0...127]的ASCII范围。


How do I set a random number of random lowercase character ... 如何设置随机数的随机小写字符...

drand48() provides a random value [0...1.0). drand48()提供随机值[0 ... 1.0)。 Scale by 26 and truncate to get 26 different indexes. 按26缩放并截断以获得26个不同的索引。

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 Pedantic代码会担心一些可能使乘积取为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. 选择一个随机长度将使用相同的方法,但是使用NUMLTRS而不是26。

int length = (int) (drand48()*NUMLTRS); 
if (index >= NUMLTRS) index = NUMLTRS -1;

... to a Struct member using memset in C ...到在C中使用memset的Struct成员

It is unclear if dns_name[] should be all the same, or generally different letters. 尚不清楚dns_name[]是否应全部相同或通常不同。

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[]是一个字符串 ,以便以后使用,请声明+1大小

dns_name[NUMLTRS + 1];

// above code

foo.dns_name[NUMLTRS] = '\0'; // append null character
printf("dna_name <%s>\n", foo.dns_name);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM