Search code examples
cdynamic-memory-allocationstrcat

Copy n words in a single string using strcat


How can i copy n different words in a single string using strcat? This is my code but doesn't work. The size of the single words is 40. arr contain the different words and fin is my final string.

char *cat(char **arr,int n){
    int i;
    char *fin;
    fin = malloc(n*40);
    for(i=0;i<n;i++){
        strcat(arr[i],fin);
    }
    return fin;
}

Solution

  • to concatenate the strings from arr info fin you need to reverse the order of argument, so replace

    strcat(arr[i],fin);
    

    by

    strcat(fin, arr[i]);
    

    because the first argument is the destination and the second the source.

    But that suppose to initialize fin to be an empty string, so before the loop do

    *fin = 0;
    

    The size of the single words is 40

    warning if you speak about the length rather than the size including the terminating null character you need to allocate one more :

    fin = malloc(n*40 + 1);
    

    From your remark :

    Moreover it is all joined without space how can i add them between each word?

    if you want to add a space you need to allocate more and to explicitly add your space, can be :

    fin = malloc(n*41+1);
    *fin = 0;
    for(i=0;i<n;i++){
        strcat(fin, arr[i]);
        strcat(fin, " ");
    }
    

    note if n large strcat search the end of fin which is more and more long, better to save the pointer to the end and use strcpy, for instance :

    char * fin = malloc(n*41+1);
    
    if (n == 0) {
      *fin = 0;
    }
    else {
      char * p = fin;
    
      for(i=0;i<n;i++){
        strcpy(p, arr[i]);
        p += strlen(p) + 1;
        p[-1]  = ' ';
      }
      p[-1]  = 0;
    }
    return fin;