Advertisement
Guest User

Copy String Using Pointer

a guest
Jul 19th, 2018
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.80 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4.  
  5. char* makeCopy(char* c)
  6. {
  7.     int len = 0, i;
  8.     char* p = c;
  9.     char* copy;
  10.  
  11.     while(*p) {
  12.         len++;
  13.         p++;
  14.     }
  15.  
  16.     // Don't forget to dynamically allocate memory for copy. I almost always forget it :(
  17.     copy = (char*) malloc(sizeof(char) * (len + 1));    // len + 1, not len because we need space for null character too.
  18.  
  19.     for (i = 0; i <= len; i++)  // I have written i <= len, not i < len, because I want to copy the null character too.
  20.         *(copy + i) = *(c + i);
  21.  
  22.     return copy;
  23. }
  24.  
  25.  
  26. int main()
  27. {
  28.     char message[1000] = "Hi there";
  29.     char *copy = makeCopy(message);
  30.  
  31.     printf("original : %s\taddress: %p\n", message, message);
  32.     printf("copy     : %s\taddress: %p\n", copy, copy);
  33.  
  34.  
  35.     return 0;
  36. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement