I have structure
typedef struct StructString {
void **string;
ringinfo RingInfo; // now i dont use it
} StructString;
I use it
StructString str;
now I try to give my str.string
value with random
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));
the RandomInput func is here
void **RandomInput(void **s, const int n) {
int i;
s = malloc((n 1) * sizeof(void *));
for (i = 0; i < n; i) {
char c=rand()8;
printf("%c ", c);
s[i]=&c;
printf("%d ", i);
printf("%c\n", *(char *)s[i]);
}
s[n]='\n';
return s;
}
and I have two problems:
- sometimes there is "" char (use the screenshot)
str.string
not what it should be (we can understand what it should be using the screenshot)
help me please, I don't understand
CodePudding user response:
- As the printable ascii characters are ranged between 0x20 (whitespace)
and 0x7e (tilda), you can randomly pick one with
rand() % ('~' - ' ' 1) ' '
orrand() % 95 32
. - If you do not have a specific reason, it will be better to define
the data type of string as
char *
, notvoid **
. Otherwise the assigned sequence of characters may have gaps between characters. - You need to terminate the string
s
with a null character instead of a newline.
Then the rewrited code will look like:
#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;
}