简体   繁体   中英

bug in function (?) and I don't understand

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:

  1. sometimes there is "" char (use the screenshot)
  2. str.string not what it should be (we can understand what it should be using the screenshot) 在此处输入图像描述

help me please, I don't understand

  • As the printable ascii characters are ranged between 0x20 (whitespace) and 0x7e (tilda), you can randomly pick one with rand() % ('~' - ' ' + 1) + ' ' or rand() % 95 + 32 .
  • If you do not have a specific reason, it will be better to define the data type of string as char * , not void ** . 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;
}

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.

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