Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Osman Zakir
- // 10 / 12 / 2017
- // Bjarne Stroustrup: Programming: Principles and Practice Using C++ 2nd Edition
- // Chapter 18 Exercise 1
- // Exercise Specifications:
- /**
- * Write a function, char* strdup(const char*), that copies a C-style string
- * into memory it allocates on the free store. Do not use any standard li-
- * brary functions. Do not use subscripting; use the dereference operator *
- * instead.
- */
- #include "../../cust_std_lib_facilities.h"
- #include <iostream>
- char *strdup(const char *src);
- int str_len(const char *str);
- void str_cpy(char *dst, const char *src);
- int main()
- {
- char *str = const_cast<char*>("Osman Zakir");
- char *duplicate = strdup(str);
- for (int i = 0, n = str_len(duplicate); i < n; ++i)
- {
- std::cout << *(duplicate + i);
- }
- std::cout << '\n';
- keep_window_open();
- }
- char *strdup(const char *src)
- {
- if (src == nullptr)
- {
- error("source string cannot be null");
- }
- char *dup = new char[str_len(src)];
- str_cpy(dup, src);
- return dup;
- }
- int str_len(const char *str)
- {
- if (str == nullptr)
- {
- return -1;
- }
- int length = 0;
- for (int i = 0; *(str + i) != '\0'; ++i)
- {
- length++;
- }
- return length;
- }
- void str_cpy(char *dst, const char *src)
- {
- for (int i = 0; *(src + i) != '\0'; ++i)
- {
- *(dst + i) = *(src + i);
- }
- int length = str_len(src);
- *(dst + length) = '\0';
- }
Add Comment
Please, Sign In to add comment