0

Good day! I'm a newbie programmer and I am still confused with how to apply the concepts of C.

I am working on a project. My problem is that I have INITIALIZED certain characters and have stored them in a string (vars[28]). My goal is to generate the characters of the string in a random manner and to store the generated string in another variable, which I do not know how to.

int randnum = 0, num = 0;
char vars[28] = "|abcdefghijklmonpqrstuvwxyz."; //initialized string
char term; //where to store randomized string
int i = 0;
char choi[1];

printf ("%c", vars[0]);

srand (time(NULL));
randnum = rand() % 30; //only 30 characters maximum to be stored        

for (i = 0; i <= randnum; i++)
{
    //randomly produce vars[28] characters here and store into 'term'
}

Additional question: How do I prevent | and . to be beside each other when randomized?

Thank you!

3
  • I imagine what you want to do, is generate a string out of randomly selected characters - for that you'd need to create a string using vars[rand() % 28] in a loop matching your generated string length Commented Oct 13, 2016 at 21:20
  • Hi! Hmm, I tried putting "term[100] = vars[rand() % 28];" inside the loop, and "printf ("%s", term)" however it does not output in the terminal... What is my mistake? Commented Oct 13, 2016 at 21:26
  • term is not an array nor a char* pointer to a stirng, it is a single byte, term[100] is accessing random memory location and can result segmentation fault. Commented Oct 13, 2016 at 21:56

1 Answer 1

2

term is just single character. A string is an array of characters. Standard C strings end with a 0. So in order to create a random string your program should look like this:

int randnum = 0;
char* vars = "|abcdefghijklmonpqrstuvwxyz."; // array of alowed characters
char term[30 + 1]; // allocating an array of 30 characters + 1 to hold null terminator
int i = 0;

srand (time(NULL));
int length = rand() % 30 + 1; // random length up to 30, minimum 1 character (the +1)

for (i = 0; i < length; i++)
{
    randnum = rand() % 28; // random index to the array of allowed characters
    term[i] = vars[randnum]; // assign random character to i-th position of term
}
term[i] = '\0'; // end string

printf("%s\n", term);

I strongly suggest you follow up with a lecture on C language though - a couple first chapters (tops), should clear everything!

Sign up to request clarification or add additional context in comments.

1 Comment

OH I SEE! Thank you so much! I am still a bit confused about things regarding pointers and addresses in C and I hope to learn more in the future. This helped me a lot! Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.