[英]bug in function (?) and I don't understand
我有结构
typedef struct StructString {
void **string;
ringinfo RingInfo; // now i dont use it
} StructString;
我用它
StructString str;
现在我尝试随机给我的str.string
值
int n = 1 + rand() % 30;
printf("%d\n", n);
str.string = RandomInput(str.string, n);
printf("%s\n", *(char **)str.string);
printf("%d\n", strlen(str.string));
RandomInput 函数在这里
void **RandomInput(void **s, const int n) {
int i;
s = malloc((n+1) * sizeof(void *));
for (i = 0; i < n; ++i) {
char c=rand()%128;
printf("%c ", c);
s[i]=&c;
printf("%d ", i);
printf("%c\n", *(char *)s[i]);
}
s[n]='\n';
return s;
}
我有两个问题:
请帮帮我,我不明白
rand() % ('~' - ' ' + 1) + ' '
或rand() % 95 + 32
随机选择一个。char *
,而不是void **
。 否则,分配的字符序列可能在字符之间有间隙。s
。然后重写的代码将如下所示:
#include <stdio.h>
#include <stdlib.h>
typedef struct StructString {
char *string;
// ringinfo RingInfo; // now i dont use it
} StructString;
char *RandomInput(char *s, const int n)
{
int i;
s = malloc((n + 1) * sizeof(char)); // strictly we should check the return value
for (i = 0; i < n; ++i) {
char c = rand() % ('~' - ' ' + 1) + ' ';
// pick a printable character between ' ' and '~'
printf("%c ", c);
s[i] = c;
printf("%d ", i);
printf("%c\n", s[i]);
}
s[n] = '\0';
return s;
}
int main()
{
StructString str;
int n = 1 + rand() % 30;
printf("%d\n", n);
str.string = RandomInput(str.string, n);
printf("%s\n", str.string);
printf("%d\n", strlen(str.string));
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.