-4

I have tried to write a function in C that duplicates a string n times. Below is my code, but this does not work. Can someone help me and tell me where I am making a mistake? It should come out something like this:

Input: 4 House Output: HouseHouseHouse

char * repeat(char *str, int times)
 { char *ret = calloc(times, (strlen(str) + 1));
   while (times-- > 0)
     strcat(ret,str);
     char *b;
   b = repeat(str,times);
   printf("%s",b);
   return 0; } 
John Black
  • 41
  • 7

1 Answers1

0

Could you please try this code? I just removed the recursion and added an extra argument output, which will be allocated inside the function repeat

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void repeat(char *input, char**ouput, int times)
 { *ouput = calloc(times, (strlen(input) + 1));
   while (times-- > 0)
     strcat(*ouput,input);
   printf("%s",*ouput);
 } 
   
int main()
{
    void repeat(char *input, char**ouput, int times);
    char * ouput;
    repeat("hello",&ouput,5);

    return(0);
}
Wim
  • 181
  • 3
  • 13
  • It worked, but how can i edit the code without an extra argument output? I would like to have the function with two arguments. Like this: repeat(char *str, int times). Is this possible? – John Black Jan 29 '21 at 13:53
  • the allocation will be done inside the function repeat, the system will clean up the data of the function after exit it, so it will be dangerous to return the output as a pointer and use it in your main function you need to keep the input, output and the number of copies as argument and return the length of new output – Wim Jan 29 '21 at 14:15
  • What exactly is the problem with a function returning an allocated pointer? How does that differ from assigning to a pointer to pointer? The comment is give erroneous advice. Sadly, comments can't be downvoted. – Jonathan Leffler Jan 29 '21 at 14:33
  • Related : https://stackoverflow.com/questions/766893/how-do-i-modify-a-pointer-that-has-been-passed-into-a-function-in-c – Wim Feb 05 '21 at 14:34
  • https://stackoverflow.com/questions/1398307/how-can-i-allocate-memory-and-return-it-via-a-pointer-parameter-to-the-calling – Wim Feb 05 '21 at 14:34