cpointerscalloc

C - repeat a string for a specific number of times in anothervariable


I want to repeat a string - for example hello - for a specific number of imes - for example 3 times -, but it doesnt work :) The example should look like this: hellohellohello, but I get no output or i get HHHHHHHHHHH...

here is my code:

char *repeat_str(size_t count, char *src) {
  int length = strlen(src);
  int z = length;
  char *ausgabe = calloc((length*(count+1)), sizeof(char));
  for(int i = 0; i<=((int) count);i++){
    for(int j =0; j< length; j++){
      ausgabe[i+j+z] = src[j];
  }
  z=z*2;
  }
  //printf("%s\n", ausgabe);
  return(ausgabe);
}

If i remove the 'z' in the brackets of 'ausgabe', i get the output HHHHHHHH%, with the z I just get no output. Could bdy pls help me change this behavoiur - and more important, understant why it does that?


Solution

  • As you are always referring *src, which is fixed to the first letter of src, the result looks like repeating it. Would you please try instead:

    char *repeat_str(size_t count, char *src) {
        int length = strlen(src);
        char *ausgabe = calloc(length * count + 1, sizeof(char));
        for (int i = 0; i < count; i++) {
            for (int j = 0; j < length; j++) {
                ausgabe[i * length + j] = src[j];
            }
        }
        //printf("%s\n", ausgabe);
        return ausgabe;
    }