RicardasSim

strcat

May 13th, 2019
699
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.78 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. int main (int argc, char **argv){
  6.  
  7.     char *str;
  8.     char str1[]="First";
  9.     char str2[]=" Second";
  10.  
  11.     str = malloc(strlen(str1)+1);
  12.  
  13.     if(!str)
  14.     {
  15.         printf("error: cannot allocate memory block.\n");
  16.         return 1;
  17.     }
  18.  
  19.     strcpy(str, str1);
  20.  
  21.     printf("%s\n", str);
  22.  
  23.     //should be large enough to contain the concatenated resulting string
  24.     char *strTmp = realloc(str,strlen(str1)+strlen(str2)+1);
  25.    
  26.     if(!strTmp)
  27.     {
  28.         printf("error: cannot reallocate memory block.\n");
  29.         free(str);
  30.         return 1;
  31.     }
  32.    
  33.     str = strTmp;
  34.    
  35.     strcat(str, str2);
  36.    
  37.     printf("%s\n", str);
  38.    
  39.     free(str);
  40.  
  41. return 0;
  42. }
  43.  
  44. /*
  45. First
  46. First Second
  47. */
Advertisement
Add Comment
Please, Sign In to add comment