Search code examples
cstringpointersdynamic-memory-allocation

A function that returns a pointer for a string which is made of random letters


I am just starting to learn c. So as I said it should be just a string but I can not figure that out so I used an array. But it should be a string. It prints out nothing or just some random symbols.

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

   char* random_word(int num_letters);

   int main(void) {

   char *word = random_word(5);
   puts(word);
   free(word);
   return 0;
   }

   char* random_word(int num_letters) {
   int a = 1;
   char *word = (char*) malloc(num_letters + 1);
   char h_word[num_letters+1];
   srand((unsigned) time(NULL));
   int i;
   for(i=0;i<sizeof(h_word);i++){
       if (!i == strlen(h_word)) {
           if(a){
              h_word[i] = 65+rand()%(90-65);
              a=0;
        }else{
            h_word[i] = 65+rand()%(90-65);
            a=1;
        }
    }else h_word[i] = '\0';
 }
      word = h_word;
  return word;

}


Solution

  • There's a problem here:

    word = h_word;
    

    You're trying to copy h_word to word, but that's not the right way to do it. This just reassigns the pointer. Instead, do this:

    strcpy(word, h_word);
    

    Also, the if (!i == strlen(h_word)) is problematic, because h_word is uninitialized, so this is undefined behavior. Instead, remove that if statement and put the h_word[i] = '\0'; after the for loop.


    But why have h_word anyway? You can just remove it entirely and put word where you have h_word instead. The loop can be for (i = 0; i < num_letters; i++) {.