Write your own versions of strlen and strcpy using only pointer arithmetic, and use them on a word.
Solution
main.cpp
#include <iostream>
std::size_t my_strlen(const char* s) {
const char* p = s;
while (*p) ++p; // stop at '\0'
return static_cast<std::size_t>(p - s);
}
char* my_strcpy(char* dest, const char* src) {
char* d = dest;
while ((*d++ = *src++)) {} // copies the '\0' too
return dest;
}
int main() {
const char* word = "LearnFrenzy";
char buffer[32];
my_strcpy(buffer, word);
buffer[0] = 'l';
std::cout << my_strlen(word) << ' ' << buffer << ' ' << word << '\n';
return 0;
}
Output Verified by compiling and running
11 learnFrenzy LearnFrenzy
The length is the distance between the start and the terminating '\0'. The copy loop assigns and advances both pointers in one expression and ends after copying the terminator.
More Pointers and Dynamic Memory practice questions
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!