Generate random char/digit

2.1k Views Asked by At

I`m trying to found fastest way to generate random digit/char array.

char *randomGet(int num) {
    srand(time(NULL));
    const char ab[37] = { "0123456789ABCDEFGHIGKLMNOPQRSTUVWXYZ" };//Alphabet&Digit
    char *targ = new char[num];
    for (int i = 0; i < num; i++) {
        strcat(targ, ab[rand() % 38]);
    }
    return targ;
}

So far I've come up with this, but it does not work (argument of type char is incompatible with parameter of type const char *). Help me find the best solution to my problem. Ty.

2

There are 2 best solutions below

0
Remy Lebeau On BEST ANSWER

strcat() takes a char* as input, but you are giving it a single char instead, thus the compiler error.

Also, the buffer that strcat() writes to must be null terminated, but your targ buffer is not null terminated initially, and you are not allocating enough space for a final null terminator anyway.

You don't need to use strcat() at all. Since you are looping anyway, just use the loop counter as the index where to write in the buffer:

Also, you are using the wrong integer value when modulo the return value of rand(). You are producing a random index that may go out of bounds of your ab[] array.

Try this instead:

char *randomGet(int num)
{
    srand(time(NULL));
    static const char ab[] = "0123456789ABCDEFGHIGKLMNOPQRSTUVWXYZ"; //Alphabet&Digit
    char *targ = new char[num+1];
    for (int i = 0; i < num; ++i) {
        targ[i] = ab[rand() % 36];
    }
    targ[num] = '\0';
    return targ;
}
0
Pete Becker On

I'd make two changes. First, make the internal source array static:

static const char ab[] = "0123456789ABCDEFGHIGKLMNOPQRSTUVWXYZ";

Note that this version does not specify the array size; the compiler will figure it out from the initializer.

Second, pass in a pointer to the target array:

void randomGet(char* targ, int num) {
    static const char ab[] = "0123456789ABCDEFGHIGKLMNOPQRSTUVWXYZ";
    for (int i = 0; i < num - 1; ++i)
        targ[i] = ab[rand() % (sizeof ab - 1)];
    targ[num - 1] = '\0';
}

This way, the caller decides how to allocate memory for the string.