Click here to Skip to main content
15,666,844 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
the funtion should work in the following way :
repeat(3, "foo") s
and returns

we have the following code :
char *repeat(size_t n, char *s) {

  char *array = malloc(sizeof(char) * strlen(s) * (1 + n)); //Q1

  for (int i = 0; i < strlen(s) * n; i++) {  //Q2

    array[i] = s[i % strlen(s)];

  array[strlen(s) * n] = 0;  //Q3

  return array;


Q1: does someone know why we write (n+1) anstead of (n) ?
Q2: why to write (strlen(s) * n )
Q3: why to write at the end array[strlen(s) * n] = 0;
Q4: why we dont write free after we allocated the array ?

What I have tried:

Updated 29-May-21 4:25am
Patrice T 29-May-21 10:22am    
What are your answers to the 4 questions.

Most of your questions can be answered here: C - Strings - Tutorialspoint[^]

As for Q4: Assume that free() makes the previously allocated memory block totally inaccessible going forward. Think about what might happen later in your program if you called free before you return from the function. What can the caller do with the returned pointer?
Share this answer
Q1: Because whoever wrote that doesn't know what they are doing: you need the (length times n) + 1 characters to allow for the trailing null.

Q2: So you go round the loop the right number of times.

Q3: Similar to Q1: Because whoever write that doesn't know how to write efficient or even easily readable code.

Q4: See K5054's answer.

Would I write the code like that? No. I'd get the string length once, and use two nested loops and a pointer, or a pointer and the standard library strcpy function in a single loop. Probably the latter.
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900