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



我被迫使用memset和drand48((来设置一个随机数(2-7(的小写字母随机字符('a'到'z'(。我的代码返回非ASCII字符,我不知道为什么。

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

我的代码处于for循环中:

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

我的代码返回非ASCII字符,我不知道为什么。

用于生成小写字母的小数位数错误

转换成整数类型的CCD_ 1可以容易地产生122个不同的值。[97…218]。这超出了[0...127]的ASCII范围。


如何设置随机小写字符的随机数。。。

drand48()提供一个随机值[0…1.0(。按26缩放并截断得到26个不同的索引。

int index = (int) (drand48()*26);  // 0...25

教学代码会关注少数几个随机值,这些值可能将产品舍入为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];

选择随机长度将使用相同的方法,但使用NUMLTRS而不是26。

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

。。。到使用C 中的memset的Struct成员

不清楚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
}
}

最后,如果为了便于以后使用,dns_name[]字符串,请使用+1大小的声明

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

最新更新