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()%128;
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:
str.string
not what it should be (we can understand what it should be using the screenshot) help me please, I don't understand
rand() % ('~' - ' ' + 1) + ' '
or rand() % 95 + 32
.char *
, not void **
. Otherwise the assigned sequence of characters may have gaps between characters.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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.