DragonOsman

chapter18ex1

Oct 12th, 2017
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.36 KB | None | 0 0
  1. // Osman Zakir
  2. // 10 / 12 / 2017
  3. // Bjarne Stroustrup: Programming: Principles and Practice Using C++ 2nd Edition
  4. // Chapter 18 Exercise 1
  5. // Exercise Specifications:
  6. /**
  7.  * Write a function, char* strdup(const char*), that copies a C-style string
  8.  * into memory it allocates on the free store. Do not use any standard li-
  9.  * brary functions. Do not use subscripting; use the dereference operator *
  10.  * instead.
  11.  */
  12.  
  13. #include "../../cust_std_lib_facilities.h"
  14. #include <iostream>
  15.  
  16. char *strdup(const char *src);
  17. int str_len(const char *str);
  18. void str_cpy(char *dst, const char *src);
  19.  
  20. int main()
  21. {
  22.     char *str = const_cast<char*>("Osman Zakir");
  23.     char *duplicate = strdup(str);
  24.     for (int i = 0, n = str_len(duplicate); i < n; ++i)
  25.     {
  26.         std::cout << *(duplicate + i);
  27.     }
  28.     std::cout << '\n';
  29.     keep_window_open();
  30. }
  31.  
  32. char *strdup(const char *src)
  33. {
  34.     if (src == nullptr)
  35.     {
  36.         error("source string cannot be null");
  37.     }
  38.     char *dup = new char[str_len(src)];
  39.     str_cpy(dup, src);
  40.     return dup;
  41. }
  42.  
  43. int str_len(const char *str)
  44. {
  45.     if (str == nullptr)
  46.     {
  47.         return -1;
  48.     }
  49.     int length = 0;
  50.     for (int i = 0; *(str + i) != '\0'; ++i)
  51.     {
  52.         length++;
  53.     }
  54.     return length;
  55. }
  56.  
  57. void str_cpy(char *dst, const char *src)
  58. {
  59.     for (int i = 0; *(src + i) != '\0'; ++i)
  60.     {
  61.         *(dst + i) = *(src + i);
  62.     }
  63.     int length = str_len(src);
  64.     *(dst + length) = '\0';
  65. }
Add Comment
Please, Sign In to add comment