String concatenation without strcat in C

前端 未结 7 806
伪装坚强ぢ
伪装坚强ぢ 2021-01-13 13:44

I am having trouble concatenating strings in C, without strcat library function. Here is my code

#include
#include
#include<         


        
7条回答
  •  既然无缘
    2021-01-13 14:40

    It is better to factor out your strcat logic to a separate function. If you make use of pointer arithmetic, you don't need the strlen function:

    #include 
    #include 
    #include  /* To completely get rid of this, 
                           implement your our strcpy as well */
    
    static void 
    my_strcat (char* dest, char* src)
    {
      while (*dest) ++dest;
      while (*src) *(dest++) = *(src++);
      *dest = 0;
    }
    
    int 
    main()
    {
      char* a1 = malloc(100);
      char* b1 = malloc(100);
    
      strcpy (a1, "Vivek");  
      strcpy (b1, " Ratnavel");
    
      my_strcat (a1, b1);
      printf ("%s\n", a1); /* => Vivek Ratnavel */
    
      free (a1);
      free (b1);
      return 0;
    }
    

提交回复
热议问题