hey everyone, im tryin to generate random strings and store them in an array. can anyone please show me?

Generating random strings as a whole is tough ...
You could chose a random length and then chose random chars to fill that length

yes, i know i need a length.
for example:

my_string="abcdefghijklmnopqrstuvwxz"; //these are my random chars
char list[10]; //the array where i want to store the randomly generated chars

now how can i do that.
i only know how to generate random integers

Look at ASCII table and note the decimal values of chars you want to randomize. Then randomize values, then print them with using "%c" placeholder. For example;

char example = 97;
int exapmleinteger = 97;
printf("%c", example );
printf("%c", exampleinteger );

will both output 'a'.

http://www.asciitable.com/

darkdai> my_string="abcdefghijklmnopqrstuvwxz"; //these are my random chars
Doesn't look very random. In fact, it has the same pattern that ABC's, except missing the 'y'

yes, i know i need a length.
for example:

my_string="abcdefghijklmnopqrstuvwxz"; //these are my random chars
char list[10]; //the array where i want to store the randomly generated chars

now how can i do that.
i only know how to generate random integers

strcpy() could be the function you need to save the string. As long as list[] has enough space to save the given string. That's twenty-five chars + a null terminator, in your post. Thus

my_string="abcdefghijklmnopqrstuvwxz";
char list[26];
strcpy(list, my_string);

Here's an example of generating some noise.
Another example if you need more.

Edited 6 Years Ago by Aia: n/a

the letters arent the random chars. they are the letters that i want to generate random chars from

im tryin to generate random strings and store them in an array. can anyone please show me?

It's easy if you really want random (pseudorandom) strings from a source:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

void random_fill(char s[], size_t n, const char *src)
{
    size_t src_len = strlen(src);
    size_t i;

    for (i = 0; i < n; i++)
    {
        s[i] = src[rand() % src_len];
    }
}

int main(void)
{
    const char *src = "abcdefghijklmnopqrstuvwxyz";
    const size_t n = 10;
    char s[10] = {0};

    srand((unsigned)time(NULL));
    random_fill(s, n - 1, src);
    puts(s);

    return 0;
}

Where it really gets interesting is if you don't want duplicate characters in the string.

This article has been dead for over six months. Start a new discussion instead.